aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Vs String Buffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String Vs String Buffer" Watch "String Vs String Buffer" New topic
Author

String Vs String Buffer

shiva .B krishna
Greenhorn

Joined: Apr 06, 2006
Posts: 2
Why is it that String immutable & String buffer mutable???
bnkiran kumar
Ranch Hand

Joined: Mar 02, 2006
Posts: 176
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 .


Kiran Kumar.
tapan hoskeri
Greenhorn

Joined: Jul 16, 2005
Posts: 11
shiva,
Click here for a fantastic article, which explains all you need to know...
shiva .B krishna
Greenhorn

Joined: Apr 06, 2006
Posts: 2
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

Joined: Mar 02, 2006
Posts: 176
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String Vs String Buffer
 
Similar Threads
Not able to open PDFs for IE7
what is difference in string and string buffer
how to trim a StringBuffer??!!
Diff between string and string buffer
Searching hashmap for array String [] occurences?