Friday, March 6, 2009

Strings&StringBuffer : mutable or immutable

Going by Java interview questions , very often the first question would be this. I remember during my campus interviews , this was one of the favourite and the opening questions for interviewers.
StringBuffer is mutable , String is immutable.
String s="Hello"; s =s+"World" . Then what does this mean?
A string object remains static , ie its contents remains the same. But then why on earth is variable s assigned a concatenated value ?
Well, s is a reference variable which refers to objects assigned to it on the other side of "=". The statement s+"World" creates a different memory location than where the s was pointing on to when it was holding "Hello". Why? because a string is static and immutable , once created it remains the same and can never be altered.
Hence when the statement s= s+"World" is executed, our reference variable s is assigned a different memory location which hold the value "HelloWorld"
Whereas , StringBuffer Object is mutable, that is those objects can be changed . Hence for the programs requiring a String concatenation dynamically, using StringBuffer would be more beneficial.

No comments:

Post a Comment