| String | StringBuffer | StringBuilder |
Mutable | No | Yes | Yes |
Synchronized | No | Yes | No |
Serialized | Yes | Yes | Yes |
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 |
StringBuffer sbf1 = new StringBuffer("abc"); //1st Object | |
sbf1.append("d"); //appends "d" to the 1st Object |
Author: Thiagu