Introduction
In Java, handling strings efficiently is crucial, especially when frequent modifications are involved. The StringBuffer
class is a powerful alternative to String
for such scenarios. Unlike String
, which is immutable, StringBuffer
allows modification of string content without creating a new object every time, making it ideal for performance-critical applications.
What is StringBuffer in Java?
StringBuffer
is a thread-safe, mutable sequence of characters provided by Java in the java.lang
package. It allows modification of strings (append, insert, delete, reverse, etc.) without creating new objects, which improves memory efficiency and performance.
Key Characteristics
- Mutable: The content can be changed.
- Thread-safe: Methods are synchronized, making it suitable for multi-threaded environments.
- Efficient for frequent modifications.
String vs StringBuffer vs StringBuilder
Feature | String | StringBuffer | StringBuilder |
---|---|---|---|
Mutability | Immutable | Mutable | Mutable |
Thread Safety | Not Thread-safe | Thread-safe | Not Thread-safe |
Performance | Less efficient in loops | Slower than StringBuilder but thread-safe | Fast and efficient for single-threaded use cases |
Creating a StringBuffer Object
StringBuffer sb1 = new StringBuffer(); // Creates an empty buffer with default capacity (16)
StringBuffer sb2 = new StringBuffer("Hello"); // Creates buffer initialized with "Hello"
StringBuffer sb3 = new StringBuffer(50); // Creates empty buffer with specified capacity
Common StringBuffer Methods and Examples
1. append()
Appends the specified string to this buffer.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
2. insert()
Inserts the specified string at the specified index.
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(5, ",");
System.out.println(sb); // Output: Hello, World
3. replace()
Replaces characters from start index to end index with a new string.
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java
4. delete()
Deletes characters from start index to end index.
StringBuffer sb = new StringBuffer("Hello Java");
sb.delete(5, 10);
System.out.println(sb); // Output: Hello
5. reverse()
Reverses the sequence of characters.
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
6. capacity() and ensureCapacity()
capacity()
: Returns current capacity.ensureCapacity(int minCapacity)
: Increases capacity if needed.
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // Default is 16
sb.ensureCapacity(50);
System.out.println(sb.capacity()); // At least 50
Scenario Examples
Scenario 1: Building a Large String Efficiently
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(", ");
}
System.out.println(sb.substring(0, 50) + "...");
Why StringBuffer?
Using String
would create a new object on each iteration, leading to performance overhead.
Scenario 2: Multi-threaded Environment
public class StringBufferExample {
private static StringBuffer buffer = new StringBuffer();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> buffer.append("A"));
Thread t2 = new Thread(() -> buffer.append("B"));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(buffer.toString()); // Output: AB or BA (depends on thread scheduling)
}
}
When to Use StringBuffer vs StringBuilder
- Use
StringBuffer
when working in multi-threaded environments where thread safety is needed. - Use
StringBuilder
when thread safety is not required for better performance.
Important Points to Remember
StringBuffer
is synchronized, making it thread-safe.- Always prefer
StringBuilder
for non-concurrent scenarios due to better performance. StringBuffer
’s capacity grows automatically but can be managed usingensureCapacity()
.
Conclusion
StringBuffer
is a powerful tool in Java for mutable and thread-safe string manipulation. Understanding its methods and appropriate use cases is key to writing efficient Java applications.