StringBuilder vs StringBuffer & Buffer Capacity Expansion
1Concept
Repeated String concatenation with `+` in loops creates intermediate throwaway objects. `StringBuilder` provides a mutable character array that appends characters in-place without heap allocations. `StringBuffer` is synchronized (thread-safe) but slower; `StringBuilder` is unsynchronized and preferred in 99% of single-threaded code.
2Architecture Diagram
Buffer Capacity Growth: Initial Capacity: 16 chars ---> When exceeded: newCapacity = (oldCapacity * 2) + 2
3Code Example
Core Java
public class StringBuilderDemo {
public static void main(String[] args) {
// Specifying initial capacity eliminates array resizing
StringBuilder sb = new StringBuilder(64);
sb.append("SELECT * FROM users ");
sb.append("WHERE status = '").append("ACTIVE").append("' ");
sb.append("ORDER BY id DESC;");
String query = sb.toString();
System.out.println("Generated SQL Query: " + query);
System.out.println("Buffer Length: " + sb.length() + " | Allocated Capacity: " + sb.capacity());
}
}4Expected Output
Generated SQL Query: SELECT * FROM users WHERE status = 'ACTIVE' ORDER BY id DESC; Buffer Length: 60 | Allocated Capacity: 64
5Key Takeaways
- ✓Always initialize StringBuilder with an estimated capacity to prevent multiple internal array reallocations.
- ✓Modern javac automatically converts simple `str1 + str2` concatenations to `invokedynamic` (StringConcatFactory).
- ✓Use StringBuffer ONLY when multiple threads concurrently mutate the same buffer.