3.2 String vs StringBuilder vs StringBuffer
← Back to Chapter 3: Strings in Java
When manipulating text in performance-critical loops, choosing the correct String abstraction prevents massive Heap memory churn and GC pressure.
StringBuilder
For repeated String modification, use StringBuilder.
StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" ");
sb.append("Developer");
System.out.println(sb.toString());
Output:
Java Developer
Unlike String, StringBuilder is mutable.
That means its existing object can be modified.
StringBuffer
StringBuffer is also mutable.
StringBuffer sb = new StringBuffer();
sb.append("Java");
sb.append(" Developer");
System.out.println(sb);
Major Differences
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable (new instance on change) | Mutable (modifies internal buffer) | Mutable (modifies internal buffer) |
| Thread Safety | Yes (Inherently thread-safe) | No (Unsynchronized) | Yes (synchronized methods) |
| Performance | Slow for repeated concatenation | Fastest (Zero lock overhead) | Slower due to synchronization locks |
| Introduced | Java 1.0 | Java 5 | Java 1.0 |
| Primary Use Case | Constants, DTOs, Maps, APIs | Local text assembly, loops | Multithreaded shared string building |
String vs StringBuilder vs StringBuffer
Remember this simple rule:
Need an unchanging String?
↓
String
Need to modify String frequently?
↓
StringBuilder
Need mutable String + synchronized operations?
↓
StringBuffer
when thread safety isn't required.
StringBuilder > StringBuffer
when thread safety is required.
StringBuffer > StringBuilder