We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,201 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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?

3
Contributors
3
Replies
23 Hours
Discussion Span
6 Months Ago
Last Updated
5
Views
Question
Answered
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
Moderator
8,521 posts since Apr 2008
Reputation Points: 2,583
Solved Threads: 1,456
Skill Endorsements: 30

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.

jalpesh_007
Posting Whiz
336 posts since Sep 2010
Reputation Points: 4
Solved Threads: 36
Skill Endorsements: 4

Thanks guys!

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

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0747 seconds using 2.78MB