Tuesday, July 13, 2010

String Vs. StringBuffer Vs. StringBuilder


String

StringBuffer

StringBuilder

Mutable

No

Yes

Yes

Synchronized

No

Yes

No

Serialized

Yes

Yes

Yes



When to use these classes?

String – When your text is not going to change
StringBuffer – When your text will be changed by multiple threads
StringBuilder – When your text will be changed by a single thread

Comparison between mutable and immutable objects

String is always considered an immutable class because String objects can't be changed. Usually the "+" or concatenation operator is used to add a character sequence to an existing String variable, but that does not mean its making alterations to the existing object. If you have a look at the example below first a String object is created and then it is concatenated with another String which eventually creates a new object for Str1 to refer to in the memory.


String str1 = "abc"; //1st Object

str1 = str1 + "d"; //2nd Object


The scenario is different for a StringBuffer or a StringBuilder. Once an object is created, it can be changed as many times as possible using methods like append(). If you look at the example below, 1st an object is created and later changes are made to the existing object in the memory using append method.

StringBuffer sbf1 = new StringBuffer("abc"); //1st Object


sbf1.append("d"); //appends "d" to the 1st Object




Author: Thiagu

No comments:

Post a Comment