Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5.

StringBuffer is a mutable class that is used to create and modify strings without creating new objects. It is thread-safe that means, it is safe to use in multi-threaded environments.
The following example demonstrates the use of StringBuffer:
Output:
hellojava
The append() method modifies the same StringBuffer object that proves it is mutable.
StringBuilder is a mutable class in Java similar to StringBuffer, but it is not thread-safe. It is faster than StringBuffer and it is commonly used in single-threaded applications.
The following example demonstrates the use of StringBuilder:
Output:
hellojava
Here, the same StringBuilder object is updated using append() that shows the efficient and fast string modification.
A list of differences between StringBuffer and StringBuilder classes are given below:
| StringBuffer | StringBuilder |
|---|---|
| StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. | StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. |
| StringBuffer is less efficient than StringBuilder. | StringBuilder is more efficient than StringBuffer. |
| StringBuffer was introduced in Java 1.0 | StringBuilder was introduced in Java 1.5 |
Let’s look at a program that compares the performance of the StringBuffer and StringBuilder classes.
The following example demonstrate how to test the performance of StringBuffer and StringBuilder.
Output:
Time taken by StringBuffer: 16ms Time taken by StringBuilder: 0ms
In the above example, both StringBuffer and StringBuilder append a string multiple times, but StringBuilder executes faster because it is not synchronized, whereas StringBuffer is thread-safe and has extra overhead.
We request you to subscribe our newsletter for upcoming updates.