String objects cannot be modified after creation. However, StringBuilder and StringBuffer allow changes to the same object, which can improve 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.
- Mutable: contents can be changed without creating new objects
- Thread-safe: methods are synchronized
Syntax
StringBuffer sb = new StringBuffer("Hello");
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.
- Mutable: allows in-place modification
- Not thread-safe: no synchronization
Syntax
StringBuilder sb = new StringBuilder("Hello");
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 not synchronized. If multiple threads access it concurrently, external synchronization is required. |
| Due to synchronization, StringBuffer is called a thread safe class. | Since its methods are not synchronized, StringBuilder is not thread-safe. |
| Due to synchronization overhead, StringBuffer may be slightly slower than StringBuilder in single-threaded scenarios. | 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. |