Both 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 a character, or getting a substring, all results in a new String object.
Anyway, when StringBuffer was introduced it has its own problem e.g. it was synchronized, methods like append have synchronized and hence they were slower. Even if you use them by just one thread and don’t share with other threads, the cost of acquiring and releasing lock due to Synchronization is still significant.
Since StringBuffer is mostly used as local mutable String variable making it synchronized wasn’t a great decision and Java designer realized their mistake and corrected it in Java 1.5 by introducing the StringBuilder class.
As I have said that both StringBuffer and StringBuilder are a mutable alternative of String class and you can change the content without creating additional objects. With String example program in java
Here are some more key differences between StringBuilder and StringBuffer in Java:
StringBuffer is present in Java and StringBuilder was added in Java 5.
Both StringBuffer and StringBuilder represents mutable String which means you can add/remove characters, substring without creating new objects.
You can convert a StringBuffer into String by calling toString() method.
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.
StringBuffer is synchronized which means all method which modifies the internal data of StringBuffer is synchronized e.g. append(), insert() and delete(). On the contrary, StringBuilder is not synchronized.
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.
Another side effect of synchronization is speed. Since StringBuffer is synchronized its lot slower than StringBuilder.
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.
In general, you should always use StringBuilder for String concatenation and creating dynamic String unless and until you are absolutely sure that you need StringBuffer.
The string concatenation done using + (plus) operator internally uses StringBuffer or StringBuilder depending upon which Java version you are using. For example, if you are running in Java 5 or higher than StringBuilder will be used and for the lower version, StringBuffer will be used.
Related blog:
Spring boot interview questions
Recommended Posts