Introduction
When working with text in Java, developers often need to modify strings by appending, inserting, deleting, or replacing characters. While the String class is widely used for storing text, it has one important limitation: Strings are immutable. This means that every time you modify a String, Java creates a new object in memory, which can reduce performance when many modifications are performed.
To solve this problem, Java provides the StringBuilder class. Unlike String, StringBuilder is mutable, meaning its contents can be changed without creating a new object. This makes it much faster and more memory-efficient for applications that perform frequent string manipulations.
The StringBuilder class belongs to the java.lang package and was introduced in Java 5 as a faster alternative to StringBuffer when thread safety is not required.
What is Java StringBuilder?
StringBuilder is a mutable sequence of characters that allows you to modify text without creating new objects.
Unlike the String class, operations such as append, insert, delete, and replace modify the existing object instead of creating a new one.
For example:
StringBuilder sb = new StringBuilder("Java");
You can then modify the object directly:
sb.append(" Programming");
The original object is updated instead of creating a new one.
Why Use StringBuilder?
Suppose you need to build a long sentence by repeatedly concatenating strings.
Using String:
String text = "";
text += "Java ";
text += "is ";
text += "awesome.";
Each concatenation creates a new String object.
Using StringBuilder:
StringBuilder text = new StringBuilder();
text.append("Java ");
text.append("is ");
text.append("awesome.");
Only one object is modified, making the program significantly faster.
Creating a StringBuilder
There are multiple ways to create a StringBuilder.
1. Empty StringBuilder
StringBuilder sb = new StringBuilder();
2. With Initial Text
StringBuilder sb = new StringBuilder("Java");
3. With Initial Capacity
StringBuilder sb = new StringBuilder(100);
This allocates space for 100 characters, reducing memory reallocations when many characters are added.
Basic Example
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb);
}
}
Output
Common StringBuilder Methods
The StringBuilder class provides many useful methods for modifying text.
| Method | Description |
|---|---|
| append() | Adds text at the end |
| insert() | Inserts text at a specific position |
| replace() | Replaces part of the text |
| delete() | Deletes characters |
| deleteCharAt() | Removes a character at an index</td |
| reverse() | Reverses the sequence |
| length() | Returns the number of characters |
| capacity() | Returns current storage capacity |
| charAt() | Returns the character at an index |
| setCharAt() | Updates a character |
| substring() | Returns part of the sequence |
| toString() | Converts to a String |
append() Method
The append() method adds data to the end of the StringBuilder.
StringBuilder sb = new StringBuilder("Java");
sb.append(" Tutorial");
System.out.println(sb);
Output
You can append strings, characters, numbers, booleans, and other data types.
insert() Method
The insert() method inserts text at a specified index.
StringBuilder sb = new StringBuilder("Java");
sb.insert(4, " Programming");
System.out.println(sb);
Output
replace() Method
The replace() method replaces characters within a specified range.
StringBuilder sb = new StringBuilder("Java Programming");
sb.replace(5, 16, "Developer");
System.out.println(sb);
Output
delete() Method
The delete() method removes characters from a range.
StringBuilder sb = new StringBuilder("Java Programming");
sb.delete(4, 16);
System.out.println(sb);
Output
deleteCharAt() Method
This method removes a single character.
StringBuilder sb = new StringBuilder("Javva");
sb.deleteCharAt(3);
System.out.println(sb);
Output
reverse() Method
The reverse() method reverses the character sequence.
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);
Output
length() Method
The length() method returns the number of characters.
StringBuilder sb = new StringBuilder("Programming");
System.out.println(sb.length());
Output
capacity() Method
Every StringBuilder has a capacity that determines how many characters it can hold before allocating more memory.
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity())
Output
When created with a String:
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.capacity());
Output
Capacity = String length + 16
setCharAt() Method
The setCharAt() method modifies a character at a given index.
StringBuilder sb = new StringBuilder("Java");
sb.setCharAt(0, 'K');
System.out.println(sb);
Output
Converting to String
You can convert a StringBuilder to a String using toString().
StrinBuilder sb = new StringBuilder("Java");
String text = sb.toString();
System.out.println(text);
Output
String vs StringBuilder
| Feature | String | StringBuilder | |
|---|---|---|---|
| Mutable | No | Yes | |
| Thread-safe | Yes (Immutable) | No | |
| Performance | Slower for repeated modifications | Faster | |
| Memory Usage | More objects created | Reuses the same object | |
| Suitable For | Fixed text | Frequently changing text |
StringBuilder vs StringBuffer
| Feature | StringBuilder | StringBuffer | |
|---|---|---|---|
| Thread-safe | No | Yes | |
| Performance | Faster | Slightly slower | |
| Synchronization | No | Yes | |
| Recommended For | Single-threaded applications | Multi-threaded applications |
Real-Life Example
Suppose you are generating an invoice.
public class Invoice {
public static void main(String[] args) {
StringBuilder bill = new StringBuilder();
bill.append("Invoice\n");
bill.append("Customer: Rahul\n");
bill.append("Product: Laptop\n");
bill.append("Price: ₹65000\n");
System.out.println(bill);
}
}
Customer: Rahul
Product: Laptop
Price: ₹65000
This approach is much more efficient than repeatedly concatenating Strings.
Advantages of StringBuilder
- High performance for repeated modifications
- Mutable object
- Reduces unnecessary memory allocation
- Rich set of methods
- Easy to use
- Better than String for loops and dynamic text generation
Disadvantages of StringBuilder
- Not thread-safe
- Cannot be shared safely between multiple threads
- Slightly more complex than using String for simple text
Common Mistakes
1. Using String Instead of StringBuilder in Loops
Incorrect:
String text = "";
for(int i = 1; i <= 1000; i++) {
text += i;
}
This creates many temporary String objects.
Correct:
StringBuilder text = new StringBuilder();
for(int i = 1; i <= 1000; i++) {
text.append(i);
}
2. Forgetting to Convert to String
Incorrect:
StringBuilder sb = new StringBuilder("Java");
If a method expects a String, convert it:
String text = sb.toString();
3. Using StringBuilder in Multi-threaded Applications
StringBuilder is not synchronized.
For thread-safe string modifications, use StringBuffer.
4. Assuming Capacity Equals Length
StringBuilder sb = new StringBuilder();
System.out.println(sb.length());
System.out.println(sb.capacity());
Output
16
- length() returns the number of characters.
- capacity() returns the allocated storage space.
Best Practices
- Use StringBuilder for repeated string concatenation.
- Prefer append() instead of using the + operator in loops.
- Specify an initial capacity if the expected size is known.
- Convert to String using toString() only when needed.
- Use StringBuffer instead of StringBuilder when thread safety is required.
- Use String for constant or rarely modified text.
Conclusion
The Java StringBuilder class is a powerful and efficient tool for handling dynamic text. Because it is mutable, it avoids creating unnecessary objects during string manipulation, resulting in better performance and lower memory usage compared to the String class.
Whenever your application needs to repeatedly append, insert, replace, or delete text—such as generating reports, building HTML, creating JSON or XML data, or processing user input—StringBuilder is usually the best choice. Understanding its methods, capacity management, and differences from String and StringBuffer will help you write faster, cleaner, and more efficient Java applications.