Pages

StringBuffer and StringBuilder are two important classes in Java which represents mutable String i.e. the String object, whose value can be changed. Since String is Immutable in Java, any change or operation on String object e.g. converting it to upper or lower case, adding character, removing character or substring all result in a new String object. This can put a lot of pressure on Garbage collector if your application generates lots of throws away String instances, to avoid this issue, Java designer presented initially StringBuffer class and later StringBuilder. When StringBuffer was introduced it has its own problem e.g. it was synchronized and hence was a lot slower.

Since it is mostly used as local variable making it synchronized wasn't a great decision and Java designer realizes their mistake and corrected it in Java 1.5 by introducing StringBuilder class. StringBuilder was nothing but a drop in like to like a class for StringBuffer except that its method was not synchronized. In this article, I'll tell you some of the important points you should know about StringBuilder and StringBuffer class.

10 Differences between StringBuffer and StringBuilder in Java

1) StringBuffer is present in Java and StringBuilder was added in Java 5.

2) Both StringBuffer and StringBuilder represents mutable String which means you can add/remove characters, substring without creating new objects.

3) You can convert a StringBuffer into String by calling toString() method.

4) Both StringBuilder and StringBuffer doesn't override equals() and hashCode() method because they are mutable and not intended to be used as a key in hash based collection classes e.g. HashMap, Hashtable, and HashSet.

5) StringBuffer is synchronized which means all method which modifies the internal data of StringBuffer is synchronized e.g. append(), insert() and delete(). On contrary, StringBuilder is not synchronized.

6) Because of synchronization StringBuffer is considered thread safe e.g. multiple threads can call its method without compromising internal data structure but StringBuilder is not synchronized hence not thread safe. See Java, A Beginners Guide for more details.

7) Another side effect of synchronization is speed. Since StringBuffer is synchronized its lot slower than StringBuilder.

8) The default length of StringBuffer is 16 characters. You should explicitly define the size of it, especially if you know that size would be less or more than 16 to avoid wasting memory and spending time during resize.