☕ Java Beginner

What is the difference between String, StringBuilder, and StringBuffer?

Answer

String is immutable — every modification creates a new object, making it inefficient for repeated string building. StringBuilder is mutable and allows in-place modification without creating new objects — ideal for building strings in loops. It is not thread-safe but faster because it has no synchronization overhead. StringBuffer is identical to StringBuilder but thread-safe (all methods are synchronized) — use it only in multi-threaded contexts where multiple threads modify the same buffer. For single-threaded string building, always prefer StringBuilder over StringBuffer for performance.