String objects cannot be modified after creation,But StringBuilder and StringBuffer allow changes to the same object, improving performance in many scenarios.
StringBuffer Class
StringBuffer is a mutable sequence of characters that is thread-safe. It is designed for multi-threaded environments where multiple threads may modify the same string object.Its features includes following:
- Mutable: contents can be changed without creating new objects
- Thread-safe: methods are synchronized
- Suitable for multi-threaded applications
- Slightly slower due to synchronization overhead
Syntax
StringBuffer sb = new StringBuffer("Hello");
Example:
class Test {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = sb1;
sb1.append(" World");
if (sb1 == sb2)
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output
Same
Explanation:
- sb1 and sb2 refer to the same StringBuffer object
- The append() method modifies the existing object
- No new object is created during modification
- Both references still point to the same memory location
StringBuilder
StringBuilder is a mutable sequence of characters similar to StringBuffer, but it is not thread-safe. It is optimized for single-threaded environments where performance is critical. Its feature includes following:
- Mutable: allows in-place modification
- Not thread-safe: no synchronization
- Faster than StringBuffer
- Ideal for single-threaded applications
Syntax
StringBuilder sb = new StringBuilder("Hello");
Example:
class Test {
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder("Hello");
StringBuilder sb2 = sb1;
sb1.append(" World");
if (sb1 == sb2)
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output
Same
Explanation:
- sb1 and sb2 reference the same object
- append() updates the existing StringBuilder instance
- No new object is created after modification
- Faster execution due to lack of synchronization
StringBuilder vs StringBuffer in Java
Below is the key differences table of StringBuffer and StringBuilder.
| StringBuffer | StringBuilder |
|---|---|
| StringBuffer is present since early versions of Java. | StringBuilder was introduced in Java 5 (JDK 1.5). |
| StringBuffer is synchronized. This means that multiple threads cannot call the methods of StringBuffer simultaneously. | StringBuilder is asynchronized. This means that multiple threads can call the methods of StringBuilder simultaneously. |
| Due to synchronization, StringBuffer is called a thread safe class. | Due to its asynchronous nature, StringBuilder is not a thread safe class. |
| Due to synchronization, StringBuffer is lot slower than StringBuilder. | Since there is no preliminary check for multiple threads, StringBuilder is a lot faster than StringBuffer. |
Use in multi-threaded environments. | Use in single-threaded or non-concurrent environments. |