3. StringBuilder vs StringBuffer
StringBuilder is the go-to for mutable string construction in single-threaded code; StringBuffer is its thread-safe but slower predecessor โ almost never needed in modern Java.
Explanation
Both StringBuilder and StringBuffer are mutable sequences of characters that avoid the repeated object creation of string concatenation. They share the same API: append(), insert(), delete(), reverse(), toString().
The only difference: StringBuffer synchronises every method, making it thread-safe but adding overhead. StringBuilder (added in Java 5) is unsynchronised and faster โ use it whenever your builder is local to a method or not shared between threads, which is almost always the case.
In modern Java, even the Java compiler replaces simple + concatenation chains with StringBuilder operations (or, since Java 9, invokedynamic-based StringConcatFactory). But building strings in a loop with + still creates a new StringBuilder per iteration โ write it explicitly when performance matters.
Example
public class StringBuilderDemo {
public static void main(String[] args) {
// StringBuilder: fast, non-thread-safe
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append("item").append(i);
if (i < 4) sb.append(", ");
}
System.out.println(sb.toString()); // item0, item1, item2, item3, item4
// Chaining is fluent
String result = new StringBuilder()
.append("Java")
.append(" ")
.append(21)
.reverse() // "12 avaJ"
.toString();
System.out.println(result);
// StringBuffer: same API, every method synchronized
StringBuffer safeBuf = new StringBuffer("thread");
safeBuf.append("-safe");
System.out.println(safeBuf); // thread-safe
// In practice, use StringBuilder + external synchronization instead
}
}