StringBuilder is a mutable sequence of characters, just like StringBuffer, but itβs not thread-safe. Because it doesnβt use synchronization, itβs faster than StringBuffer in single-threaded scenarios.
Features
- Mutable: Contents can be changed without creating a new object.
- Not thread-safe, but faster than StringBuffer.
- Efficient for frequent modifications (e.g. appending in loops).
Comparison
String vs StringBuffer vs StringBuilder
Feature | String | StringBuffer | StringBuilder |
---|---|---|---|
Mutability | β | β | β |
Thread-safe | β | β | β |
Performance | π’ Slowest | π Medium | π Fastest |
Methods
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // "Hello World"
sb.insert(5, ","); // "Hello, World"
sb.replace(0, 5, "Hi"); // "Hi, World"
sb.delete(2, 3); // "HiWorld"
sb.reverse(); // "dlroW iH"
sb.length(); // Get length
sb.capacity(); // Default: 16 (or initial + 16)
sb.toString(); // Convert to String
Parent: _Strings