Java StringBuffer Deep Dive
StringBuffer is similar to StringBuilder but is thread-safe. It is synchronized, meaning multiple threads can safely access and modify a StringBuffer object.
_1747814328274.png)
Characteristics
- Mutable: Like StringBuilder, the content of a StringBuffer object can be modified.
- Thread-Safe: All methods in StringBuffer are synchronized, making it safe for use in multi-threaded environments.
Common Operations
Here are some common operations performed using StringBuffer:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
// Append
sb.append(" World"); // "Hello World"
// Insert
sb.insert(5, ","); // "Hello, World"
// Replace
sb.replace(6, 7, "-"); // "Hello- World"
// Delete
sb.delete(5, 6); // "Hello World"
// Reverse
sb.reverse(); // "dlroW olleH"
// Capacity
int capacity = sb.capacity(); // Default is 16 + length of string
}
}
Advantages
- Thread-Safe: Can be used safely in multi-threaded environments.
- Mutable: Allows efficient string manipulation.
Disadvantages
- Performance: Slower than StringBuilder due to synchronization overhead.
Comparison of String, StringBuilder, and StringBuffer
Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
Mutability | Immutable | Mutable | Mutable |
Thread-Safe | Yes | No | Yes |
Performance | Slow (due to immutability) | Fast (no synchronization) | Slower (synchronization overhead) |
Use Case | When immutability is required | Single-threaded environments with frequent modifications | Multi-threaded environments with frequent modifications |

When to Use Which?
- String:
- Use when the string value is not expected to change.
- Ideal for scenarios where immutability is important, such as keys in a HashMap.
- StringBuilder:
- Use in single-threaded environments where frequent string modifications are required.
- Ideal for scenarios like building dynamic SQL queries, constructing JSON/XML, or concatenating strings in loops.
- StringBuffer:
- Use in multi-threaded environments where frequent string modifications are required.
- Ideal for scenarios where thread safety is a concern, such as logging in multi-threaded applications.
