Introduction
String class is useful for storing text; it is immutable, meaning its content cannot be changed after the object is created. Every modification creates a new String object, which can impact performance when many changes are required.
To solve this issue, Java provides the StringBuffer class. Unlike String, StringBuffer is mutable, allowing you to modify its contents without creating a new object each time. Additionally, StringBuffer is thread-safe because its methods are synchronized, making it suitable for multi-threaded applications.
The StringBuffer class belongs to the java.lang package and has been part of Java since version 1.0. Although StringBuilder is generally faster in single-threaded applications, StringBuffer remains an excellent choice when multiple threads need to access and modify the same sequence of characters safely.
What is Java StringBuffer?
StringBuffer is a mutable sequence of characters that allows you to modify text without creating new objects.
Unlike the String class, methods such as append(), insert(), replace(), and delete() modify the existing object directly.
For example:
StringBuffer sb = new StringBuffer("Java");
You can then modify it:
sb.append(" Programming");
The same object is updated instead of creating a new one.
Why Use StringBuffer?
Suppose you need to build a long text by repeatedly adding new strings.
Using String:
String text = "";
text += "Java ";
text += "is ";
text += "powerful.";
Each concatenation creates a new object.
Using StringBuffer:
StringBuffer text = new StringBuffer();
text.append("Java ");
text.append("is ");
text.append("powerful.");
The existing object is modified, resulting in better performance and lower memory usage.
Creating a StringBuffer
There are several ways to create a StringBuffer.
1. Empty StringBuffer
StringBuffer sb = new StringBuffer();
2. With Initial String
StringBuffer sb = new StringBuffer("Java");
3. With Initial Capacity
StringBuffer sb = new StringBuffer(100);
This reserves space for 100 characters, reducing the need for memory reallocation.
Basic Example
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.append(" Tutorial");
System.out.println(sb);
}
}
Output
Common StringBuffer Methods
The StringBuffer class provides many useful methods for modifying text.
| Method | Description |
|---|---|
| append() | Adds text to the end |
| insert() | Inserts text at a specified position |
| replace() | Replaces characters |
| delete() | Deletes characters within a range |
| deleteCharAt() | Removes a character at a specific index |
| reverse() | Reverses the character sequence |
| length() | Returns the number of characters |
| capacity() | Returns the current capacity |
| charAt() | Returns the character at an index |
| setCharAt() | Changes a character |
| substring() | Returns part of the sequence |
| toString() | Converts StringBuffer to String |
append() Method
The append() method adds data to the end of the StringBuffer.
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb);
Output
You can append strings, characters, integers, floating-point numbers, booleans, and objects.
insert() Method
The insert() method inserts text at a specified index.
StringBuffer sb = new StringBuffer("Java");
sb.insert(4, " Programming");
System.out.println(sb);
Output
replace() Method
The replace() method replaces characters within a specified range.
StringBuffer sb = new StringBuffer("Java Programming");
sb.replace(5, 16, "Developer");
System.out.println(sb);
Output
delete() Method
The delete() method removes characters from a specified range.
StringBuffer sb = new StringBuffer("Java Programming");
sb.delete(4, 16);
System.out.println(sb);
Output
deleteCharAt() Method
The deleteCharAt() method removes a character from a given index.
StringBuffer sb = new StringBuffer("Javva");
sb.deleteCharAt(3);
System.out.println(sb);
Output
reverse() Method
The reverse() method reverses the character sequence.
StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
Output
length() Method
The length() method returns the number of characters.
StringBuffer sb = new StringBuffer("Programming");
System.out.println(sb.length());
Output
capacity() Method
The capacity() method returns the current storage capacity.
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
Output
When initialized with a String:
StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.capacity());
Output
The capacity is calculated as:
String Length + 16
setCharAt() Method
The setCharAt() method updates a character at a specified index.
StringBuffer sb = new StringBuffer("Java");
sb.setCharAt(0, 'K');
System.out.println(sb);
Output
Converting StringBuffer to String
You can convert a StringBuffer into a String using the toString() method.
StringBuffer sb = new StringBuffer("Java");
String text = sb.toString();
System.out.println(text);
Output
String vs StringBuffer
| Feature | String | StringBuffer |
|---|---|---|
| Mutable | No | Yes |
| Thread-safe | Yes (Immutable) | Yes |
| Performance | Slower for repeated modifications | Faster |
| Object Creation | Creates new objects | Reuses the same object |
| Best For | Fixed text | Frequently changing text in multi-threaded applications |
StringBuffer vs StringBuilder
| Feature | StringBuffer | StringBuilder |
|---|---|---|
| Thread-safe | Yes | No |
| Synchronization | Yes | No |
| Performance | Slightly slower | Faster |
| Best For | Multi-threaded applications | Single-threaded applications |
Real-Life Example
Suppose multiple threads in a banking application generate transaction reports.
public class Report {
public static void main(String[] args) {
StringBuffer report = new StringBuffer();
report.append("Transaction Report\n");
report.append("Account: 123456\n");
report.append("Deposit: ₹10,000\n");
report.append("Balance: ₹50,000");
System.out.println(report);
}
}
Output
Account: 123456
Deposit: ₹10,000
Balance: ₹50,000
Using StringBuffer ensures that concurrent modifications are handled safely.
Advantages of StringBuffer
- Mutable, allowing efficient modifications.
- Thread-safe due to synchronized methods.
- Reduces unnecessary object creation.
- Rich set of methods for text manipulation.
- Suitable for multi-threaded applications.
- Better performance than repeated String concatenation.
Disadvantages of StringBuffer
- Slower than StringBuilder because of synchronization.
- Uses slightly more resources in single-threaded programs.
- More complex than String for simple text operations.
Common Mistakes
1. Using String Instead of StringBuffer in Loops
Incorrect:
String text = "";
for(int i = 1; i <= 1000; i++) {
text += i;
}
This creates thousands of temporary objects.
Correct:
StringBuffer text = new StringBuffer();
for(int i = 1; i <= 1000; i++) {
text.append(i);
}
2. Forgetting to Convert to String
Some APIs require a String instead of a StringBuffer.
StringBuffer sb = new StringBuffer("Java");
String text = sb.toString();
3. Using StringBuffer When Thread Safety Isn't Needed
If your application is single-threaded, StringBuilder is generally a better choice because it avoids synchronization overhead.
4. Confusing length() and capacity()
StringBuffer sb = new StringBuffer();
System.out.println(sb.length());
System.out.println(sb.capacity());
Output
16
- length() returns the number of stored characters.
- capacity() returns the allocated storage space.
Best Practices
- Use StringBuffer when multiple threads modify the same text.
- Use append() instead of repeated String concatenation.
- Specify an initial capacity when working with large text.
- Convert to String only when required.
- Prefer StringBuilder for single-threaded applications.
- Use String for constant or rarely modified text.
Conclusion
The Java StringBuffer class is an essential utility for applications that require frequent string modifications in a multi-threaded environment. Unlike the immutable String class, StringBuffer allows text to be updated efficiently without creating new objects, improving both performance and memory usage.
Although StringBuilder is generally preferred for single-threaded applications due to its speed, StringBuffer remains the right choice whenever thread safety is important. Understanding its methods, capacity management, and differences from String and StringBuilder will help you write robust, efficient, and thread-safe Java applications.