Friday, August 27, 2010

String, StringBuilder and StringBuffer

StringBuilder object is mutable while String object is Immutable.

Mutable - Value can be change.
Immutable - Value can not be change.

It means when we store any thing in string we can not change its value. But It works fine when we do it. Actually a new String object is created internally to do the changes.

But this is not the case with StringBuilder, that's why String Builder is fast than String in case of append.

String sName= "Khaleek";
sName = sName + "Ahmad";


StringBuilder sbName= new StringBuilder();
sbName.Append("Ahmad");

Result would be same but second block of code will be fast.

StringBuffer and StringBuilder

StringBuffer is synchronized(Means it is thread safe) and StringBuilder is asynchronyzed(It is not thread safe.)

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

No comments:

Followers

Link