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
Feature | String | StringBuffer | StringBuilder |
---|---|---|---|
Mutability | β | β | β |
Thread-safe | β | β | β |
Performance | π’ Slowest | π Medium | π Fastest |
Methods
StringBuffer sb = new StringBuffer("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
Tip
Capacity expands as:
newCap = (oldCap * 2) + 2
when exceeded.
Parent: _Strings