• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Vs String Buffer

 
shiva .B krishna
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is it that String immutable & String buffer mutable???
 
bnkiran kumar
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shiva, String immutable means if we create an objec of string with some value, the value is final we cannot change its value.

where as for string buffer, we can change the value present in string buffer object.
like StringBuffer b=new StringBuffer("kiran");
b.append("kumar");
now b will has kirankumar, we are able to change the content of
stringbuffer but where as for string, String str=new String("kiran");
str will always has content "kiran" even after this method call str.replace('i','r'); not only replace ,it is same for any other method .
 
tapan hoskeri
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shiva,
Click here for a fantastic article, which explains all you need to know...
 
shiva .B krishna
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kiran thanks for the reply. The explanation u gave at mutable & immutable is fine But then i was asked in an interview why is String made immutable & String buffer mutable.So pls try to answer that "why"
 
bnkiran kumar
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Siva,

String class is generally used when we require constant strings, StringBuffer is generally used if we want frequent operations(like append,delete etc) on the string.
may be they have done for compiler optimization, because there is no need to create a new object if we use constant strings.
StringBuffer was created because if we use strings which change frequently everytime a new object is created if we perform any operation on it.
May be experts like moderators of this form can answer this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic