aspose file tools*
The moose likes Beginning Java and the fly likes String/StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String/StringBuffer" Watch "String/StringBuffer" New topic
Author

String/StringBuffer

Saurabh Saha
Ranch Hand

Joined: Dec 08, 2004
Posts: 52
Hi All,
please explan difference between String and StringBuffer of the following code.

String a="old"; //old object
a="new"; //new object
------------------------------
StringBuffer a="old";//old object
a="new";//new object

please tell me that is I'm right that when we change in String it create new object but for StringBuffer it keeps old object.
please explan me!

Thanks,
Vivek Mishra
David Mace
Ranch Hand

Joined: May 26, 2004
Posts: 35
Strings are read-only and immutable meaning that the value cannot be changed. When you change the value of the string as you have in the first example, you are making a new object.

Stringbuffers are faster than String objects and should be used when performing concats, etc. Traditionally a string object would be appended through something like:

String x = "xyz";
x += "abc";

Doing the same with a Stringbuffer would look something like:

String x = "xyz";
x.append("abc");

Hope that helps,
David


Dad always thought laughter was the best medicine, which I guess is why several of us died of tuberculosis. -Jack Handy
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
Originally posted by Mishra Vivek:
Hi All,
please explan difference between String and StringBuffer of the following code.

String a="old"; //old object
a="new"; //new object
------------------------------
StringBuffer a="old";//old object
a="new";//new object
Thanks,
Vivek Mishra


One problem with your code above is you cannot do:

StringBuffer a = "old";

It will not compile. You have to create a new StringBuffer with

StringBuffer a = new StringBuffer();
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String/StringBuffer
 
Similar Threads
String/StringBuffer
What would be the output?
Garbage collection error in Kathy SCJP1.5 book
had a question about string equals method
Strings and immutability