This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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


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();
 
GeeCON Prague 2014
 
subject: String/StringBuffer