Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String/StringBuffer

 
Saurabh Saha
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 35
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Steven Bell
Ranch Hand
Posts: 1071
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic