• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String/StringBuffer

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
 
reply
    Bookmark Topic Watch Topic
  • New Topic