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

FeatureStringStringBufferStringBuilder
Mutabilityβœ—βœ…βœ…
Thread-safeβœ—βœ…βœ—
Performance🐒 Slowest🐌 MediumπŸš€ Fastest

Methods

StringBuilder sb = new StringBuilder("Hello");
Modify content
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"
Info & Conversion
sb.length();             // Get length
sb.capacity();           // Default: 16 (or initial + 16)
sb.toString();           // Convert to String

Parent: _Strings