In Java, both StringBuffer
and StringBuilder
are classes used to create and manipulate mutable strings (unlike String
, which is immutable).
Hereβs the comparison:
π 1. Mutability
- Both
StringBuffer
andStringBuilder
create mutable string objects (content can be changed without creating new objects).
π 2. Thread Safety
StringBuffer
- Thread-safe, because its methods are synchronized.
- Suitable for multi-threaded environments.
- Slightly slower due to synchronization overhead.
StringBuilder
- Not thread-safe (no synchronization).
- Suitable for single-threaded environments.
- Faster than
StringBuffer
.
π 3. Performance
- StringBuffer β Slower (due to synchronization).
- StringBuilder β Faster (no synchronization).
π 4. Example
public class Test {
public static void main(String[] args) {
// Using StringBuffer
StringBuffer sb1 = new StringBuffer("Hello");
sb1.append(" World");
System.out.println("StringBuffer: " + sb1);
// Using StringBuilder
StringBuilder sb2 = new StringBuilder("Hello");
sb2.append(" World");
System.out.println("StringBuilder: " + sb2);
}
}
β Output:
StringBuffer: Hello World
StringBuilder: Hello World
π 5. When to Use
- Use
StringBuffer
if:- Multiple threads may access/modify the string simultaneously.
- Use
StringBuilder
if:- Only a single thread will modify the string (most common case).