StringBuffer sb = new StringBuffer(new String("Hello")); //Case 1
StringBuffer sb1; //Case 2
String s = new String("Hello"); // Case 2
sb1=s; //Case 2
StringBuffer sb3; //Case 3
sb3 = new String("Hello");//Case 3

Case 1 compiles fine and outputs Hello but Case 2 and Case 3 gives compiler error saying incompatible types. Why is it so?

Recommended Answers

All 3 Replies

String and StringBuffer have no "extends" relationship, so you can't assign or cast either to the other.
Case 1 works because StringBuffer has a constructor that takes a String as parameter.

String class is used to manipulate character strings that cannot be changed, objects of type String are read only and immutable.

The StringBuffer class is used to represent characters that can be modified.

You can not modify String stored in String Object,but you can modify String(Word,sentence) if you have stored it in StringBuffer Object.

So both have no relationship in between.

Thanks guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.