String & StringBuffer compatibility
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?
Related Article: Initialising a String array.
is a solved Java discussion thread by JamesCherrill that has 3 replies, was last updated 1 year ago and has been tagged with the keywords: array, initialise, string.
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
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.
JamesCherrill
... trying to help
8,521 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 6 Months Ago by
JamesCherrill
and
jalpesh_007