StringBuffer is a Java class used to create and manipulate strings that can be changed (mutable). Unlike String, which creates a new object every time it’s modified, StringBuffer allows you to update the same object, making it more memory-efficient when doing lots of string operations. It is also thread-safe, meaning it’s safe to use in multi-threaded environments.

Features

  • Mutable: Contents can be changed without creating a new object.
  • Thread-safe: Methods are synchronized to prevent race conditions race conditions.
  • Efficient for frequent modifications (e.g. appending in loops).

Comparison

String vs StringBuffer vs StringBuilder

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

Methods

StringBuffer sb = new StringBuffer("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

Tip

Capacity expands as: newCap = (oldCap * 2) + 2 when exceeded.


Parent: _Strings