All topics
library
beginner

StringBuilder vs StringBuffer

Know the difference, when to use each, and why StringBuilder replaced StringBuffer in modern code.

Both StringBuilder and StringBuffer are mutable character sequences for efficient string manipulation. They share the same API (append, insert, delete, reverse, etc.) but differ in thread safety.

StringBuilder = a private notebook (fast, only you use it). StringBuffer = a shared whiteboard with a lock (slower because you must wait for the key).

Key Concepts

1
StringBuffer: synchronized — every method acquires a lock. Thread-safe but slower. Introduced in JDK 1.0.
2
StringBuilder: not synchronized — no locking overhead. Not thread-safe but significantly faster. Introduced in Java 5.
3
In practice, string building is almost always done within a single method (local variable), so thread safety is irrelevant. StringBuilder is the default choice. StringBuffer exists only for backward compatibility.
4
Performance: StringBuilder is typically 15-30% faster than StringBuffer due to the absence of synchronization overhead. Both are dramatically faster than String concatenation in loops because they modify a mutable internal char[]/byte[] array instead of creating new objects.
5
Internal array management: both start with a default capacity of 16 characters. When the content exceeds capacity, the array grows (typically doubling). Pre-sizing with the capacity constructor avoids unnecessary copies.
6
The compiler optimizes simple String concatenation (a + b + c) into StringBuilder chains automatically (since Java 9, uses invokedynamic-based StringConcatFactory for even better performance). But loop concatenation still needs explicit StringBuilder.
a + b + c