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?

4 Years
Discussion Span
Last Post by rahul.ch

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.