StringBuilder builder = new StringBuilder("Hello");
builder.append(" Java");
System.out.println(builder);Java StringBuilder: Mutable String Operations for High Performance
Direct Answer & Core Concept
StringBuilder is a Java class used to create and modify strings efficiently. Unlike the String class, a StringBuilder object is mutable, which means its content can be changed without creating a completely new object for every modification.
This makes StringBuilder especially useful when a program performs many string operations such as concatenation, insertion, deletion, replacement, or reversing text.
For example, repeatedly using + with String inside a loop can create many temporary objects. StringBuilder avoids much of this unnecessary object creation and can provide better performance.
Detailed Explanation & Mechanics
What Is StringBuilder in Java?
StringBuilder is a class in the java.lang package that provides a mutable sequence of characters.
Unlike a normal String, the contents of a StringBuilder can be changed after the object is created.
Output:
Hello JavaThe same StringBuilder object can continue to be modified.
builder.append(" Programming");
System.out.println(builder);Output:
Hello Java ProgrammingKey idea
String is immutable, while StringBuilder is mutable.
Why Use StringBuilder?
When you need to perform many modifications to text, StringBuilder is often more appropriate than repeatedly creating new String objects.
Consider this example:
String result = "";
for (int i = 1;
i <= 5;
i++) {
result += i;
}System.out.println(result);This repeatedly creates new String objects because String is immutable.
With StringBuilder:
StringBuilder result = new StringBuilder();
for (int i = 1;
i <= 5;
i++) {
result.append(i);
}System.out.println(result);Output:
12345The builder can modify its internal character sequence instead of creating a new immutable String for every append operation.
String vs StringBuilder
The most important difference is mutability.
| Feature | String | StringBuilder |
|---|---|---|
| Mutable | No | Yes |
| Can modify existing object | No | Yes |
| String concatenation | Can be expensive in repeated operations | Generally efficient |
| Thread-safe | Immutable | No |
| Performance for many modifications | Usually lower | Usually better |
| Package | java.lang | java.lang |
| Common use | Fixed text | Frequently changing text |
Example:
String text = "Hello";
text = text + " World";A new String value is created.
With StringBuilder:
StringBuilder text = new StringBuilder("Hello");
text.append(" World");The builder itself is modified.
Creating a StringBuilder
There are several common ways to create a StringBuilder.
1. Empty StringBuilder
StringBuilder sb = new StringBuilder();This creates an empty builder.
You can add content later:
sb.append("Hello");2. StringBuilder with Initial Text
StringBuilder sb = new StringBuilder("Hello");Now the builder contains:
HelloYou can modify it:
sb.append(" Java");
System.out.println(sb);Output:
Hello Java3. StringBuilder with Initial Capacity
You can also specify the initial capacity.
StringBuilder sb = new StringBuilder(100);This creates a builder with an initial capacity suitable for approximately 100 characters.
Capacity is different from the current length.
StringBuilder sb = new StringBuilder(100);
System.out.println(sb.length());
System.out.println(sb.capacity());The length starts at:
0 while the capacity is:
100append() Method
The append() method is one of the most commonly used StringBuilder methods.
It adds content to the end of the existing sequence.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
System.out.println(sb);Output:
Hello JavaYou can append different data types.
StringBuilder sb = new StringBuilder();
sb.append("Age: ");
sb.append(35);
sb.append(", Salary: ");
sb.append(44000.50);
System.out.println(sb);Output:
Age: 35, Salary: 44000.5Appending Characters
You can append individual characters.
StringBuilder sb = new StringBuilder("Java");
sb.append('!');
System.out.println(sb);Output:
Java!Appending Boolean Values
StringBuilder sb = new StringBuilder();
sb.append("Java is popular: ");
sb.append(true);
System.out.println(sb);Output:
Java is popular: trueAppending Arrays
You can also append arrays.
char[] letters = {
'J', 'a', 'v', 'a'
};
StringBuilder sb = new StringBuilder();
sb.append(letters);
System.out.println(sb);Output:
Javainsert() Method
The insert() method adds content at a specified position.
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(6, "Java ");
System.out.println(sb);Output:
Hello Java WorldThe index determines where the new content is inserted.
Inserting a Character
StringBuilder sb = new StringBuilder("Jva");
sb.insert(1, 'a');
System.out.println(sb);Output:
JavaInserting Numbers
StringBuilder sb = new StringBuilder("Value: ");
sb.insert(7, 100);
System.out.println(sb);Output:
Value: 100delete() Method
The delete() method removes characters between two indexes.
StringBuilder sb = new StringBuilder("Hello Java");
sb.delete(5, 10);
System.out.println(sb);Output:
HelloThe starting index is included, while the ending index is excluded.
For:
delete(start, end)characters from start through end - 1 are removed.
deleteCharAt() Method
If you want to remove a single character, use deleteCharAt().
StringBuilder sb = new StringBuilder("Jvaa");
sb.deleteCharAt(2);
System.out.println(sb);Output:
JvaAnother example:
StringBuilder sb = new StringBuilder("Java");
sb.deleteCharAt(3);
System.out.println(sb);Output:
Javreplace() Method
The replace() method replaces a range of characters.
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);Output:
Hello JavaThe syntax is:
replace(start, end, newText)reverse() Method
The reverse() method reverses the contents of a StringBuilder.
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);Output:
avaJThis method is useful for simple palindrome programs and reverse-string operations.
Reverse a String Using StringBuilder
String text = "level";
StringBuilder sb = new StringBuilder(text);
sb.reverse();
System.out.println(sb);Output:
levelYou can compare the original and reversed values to check for a palindrome.
charAt() Method
charAt() returns the character at a specific index.
StringBuilder sb = new StringBuilder("Java");
char ch = sb.charAt(2);
System.out.println(ch);Output:
vIndexes start at 0.
For:
Javathe indexes are:
J → 0a → 1v → 2a → 3setCharAt() Method
Unlike String, a StringBuilder allows you to directly change a character using setCharAt().
StringBuilder sb = new StringBuilder("Jova");
sb.setCharAt(1, 'a');
System.out.println(sb);Output:
JavaThis is a good example of the mutability of StringBuilder.
length() Method
The length() method returns the number of characters currently stored.
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.length());Output:
4After modification:
sb.append(" Programming");
System.out.println(sb.length());The length changes automatically.
capacity() Method
The capacity() method returns the amount of storage currently available before the builder needs to expand its internal storage.
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());The default initial capacity is commonly 16.
You can specify a different initial capacity:
StringBuilder sb = new StringBuilder(100);
System.out.println(sb.capacity());Output:
100Capacity vs Length
These two concepts are different.
StringBuilder sb = new StringBuilder(50);
sb.append("Java");
System.out.println("Length: " + sb.length());
System.out.println("Capacity: " + sb.capacity());Possible output:
Length: 4Capacity: 50The length tells you how much text exists.
The capacity tells you how much internal storage is currently available before expansion.
ensureCapacity() Method
ensureCapacity() can be used when you expect the builder to grow.
StringBuilder sb = new StringBuilder();
sb.ensureCapacity(100);
System.out.println(sb.capacity());This requests enough capacity for at least the specified number of characters.
It can be useful when the approximate size of the final text is known in advance.
setLength() Method
setLength() changes the current length of the builder.
StringBuilder sb = new StringBuilder("Hello");
sb.setLength(3);
System.out.println(sb);Output:
HelIf the new length is larger than the current length, additional null characters are added internally.
For normal beginner programs, setLength() is less commonly needed than append(), delete(), or replace().
toString() Method
toString() converts the contents of a StringBuilder into a normal immutable String.
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" Java");
String result = sb.toString();
System.out.println(result);Output:
Hello JavaThis is commonly used when a method or API requires a String.
Important
StringBuilder is mutable, while the result returned by toString() is a String.
StringBuilder in a Loop
One of the most common uses of StringBuilder is building text inside loops.
For example:
StringBuilder sb = new StringBuilder();
for (int i = 1;
i <= 10;
i++) {
sb.append(i).append(" ");
}System.out.println(sb);Output:
1 2 3 4 5 6 7 8 9 10This is cleaner and generally more efficient than repeatedly concatenating immutable strings.
Method Chaining with StringBuilder
Many StringBuilder methods return the same builder object, allowing method chaining.
StringBuilder sb = new StringBuilder();
sb.append("Java") .append(" ") .append("Programming") .append(" ") .append("Language");
System.out.println(sb);Output:
Java Programming LanguageMethod chaining can make string-building code shorter and easier to read.
Building a Sentence
StringBuilder sentence = new StringBuilder();
sentence.append("Java");
sentence.append(" is");
sentence.append(" a");
sentence.append(" powerful");
sentence.append(" programming");
sentence.append(" language.");
System.out.println(sentence);Output:
Java is a powerful programming language.Removing Extra Characters
StringBuilder can be useful when building comma-separated data.
StringBuilder sb = new StringBuilder();
sb.append("Java, ");
sb.append("Python, ");
sb.append("PHP, ");
System.out.println(sb);Output:
Java, Python, PHP,You could remove the final comma and space:
sb.delete(sb.length() - 2, sb.length());
System.out.println(sb);Output:
Java, Python, PHPStringBuilder for CSV Data
A simple CSV-like string can be constructed efficiently.
StringBuilder csv = new StringBuilder();
csv.append("Name,Age,City\n");
csv.append("Rahul,30,Kolkata\n");
csv.append("Amit,28,Delhi\n");
System.out.println(csv);Output:
Name,Age,CityRahul,30,KolkataAmit,28,DelhiThis approach is useful when generating text output dynamically.
StringBuilder for HTML Generation
StringBuilder can also be useful for generating HTML text.
StringBuilder html = new StringBuilder();
html.append("<html>");
html.append("<body>");
html.append("<h1>Hello Java</h1>");
html.append("</body>");
html.append("</html>");
System.out.println(html);This demonstrates a practical situation where many pieces of text are combined.
For complex HTML generation, however, dedicated templating or HTML libraries are usually easier to maintain.
StringBuilder for SQL-Like Text Construction
A builder can also construct dynamic text:
StringBuilder query = new StringBuilder();
query.append("SELECT ");
query.append("name ");
query.append("FROM users ");
query.append("WHERE age > 18");
System.out.println(query);Output:
SELECT name FROM users WHERE age > 18In real applications, do not construct SQL with untrusted user input by simple string concatenation. Use parameterized queries or prepared statements to reduce SQL injection risks.
StringBuilder and Memory
Because String is immutable, repeated modifications can produce many temporary objects.
Example:
String result = "";
for (int i = 0;
i < 10000;
i++) {
result += i;
}The program may repeatedly create new strings.
A builder is designed for this type of changing text:
StringBuilder result = new StringBuilder();
for (int i = 0;
i < 10000;
i++) {
result.append(i);
}The builder maintains a mutable character sequence and grows its capacity when necessary.
StringBuilder Performance
StringBuilder is commonly preferred when a program performs many string modifications, especially inside loops.
Example:
StringBuilder sb = new StringBuilder();
for (int i = 0;
i < 100000;
i++) {
sb.append(i);
}The exact performance improvement depends on the operation, Java version, compiler optimizations, and program structure.
Therefore, do not assume that every use of StringBuilder will automatically make a program faster. Use it where repeated mutable string construction is actually needed.
StringBuilder vs String Concatenation
For simple concatenation, this is perfectly readable:
String name = "Java";
String message = "Hello " + name;There is usually no reason to replace every simple + operation with StringBuilder.
However, when text is repeatedly modified:
StringBuilder result = new StringBuilder();
for (int i = 0;
i < 1000;
i++) {
result.append(i);
}StringBuilder is a natural choice.
Practical rule
Small/simple concatenation: use +.
Repeated or complex string construction: consider StringBuilder.
StringBuilder vs StringBuffer
Java also provides StringBuffer.
Both classes provide mutable character sequences, but they have an important difference.
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Mutable | Yes | Yes |
| Thread-safe | No | Yes, through synchronization |
| Synchronization | No | Yes |
| Typical single-thread performance | Generally better | Generally lower due to synchronization overhead |
| Common use | Single-threaded string construction | Cases requiring its synchronization behavior |
Example:
StringBuilder sb = new StringBuilder("Hello");and:
StringBuffer buffer = new StringBuffer("Hello");For ordinary single-threaded string construction, StringBuilder is usually the straightforward choice.
Is StringBuilder Thread-Safe?
No.
StringBuilder is not synchronized and should not be treated as thread-safe.
For example, if multiple threads modify the same builder concurrently, the program can encounter data consistency problems.
If you need a synchronized mutable string sequence, StringBuffer is the older alternative.
However, another common solution is to avoid sharing a mutable builder between threads.
StringBuilder and String Pool
A StringBuilder object is different from a string literal.
Consider:
String text = "Java";The literal "Java" can use the Java String Pool.
But:
StringBuilder sb = new StringBuilder("Java");creates a mutable StringBuilder object containing the characters from "Java".
When you call:
String result = sb.toString();you obtain a String representation of the builder's contents.
Converting String to StringBuilder
You can create a builder from an existing string.
String text = "Hello Java";
StringBuilder sb = new StringBuilder(text);
sb.append(" Programming");
System.out.println(sb);Output:
Hello Java ProgrammingConverting StringBuilder to String
Use toString().
StringBuilder sb = new StringBuilder("Hello Java");
String text = sb.toString();
System.out.println(text);This is one of the most common conversions involving StringBuilder.
Finding a Character
You can use charAt() to access individual characters.
StringBuilder sb = new StringBuilder("Programming");
for (int i = 0;
i < sb.length();
i++) {
System.out.println(sb.charAt(i));
}This prints each character separately.
Building a String in Reverse
A common beginner exercise is reversing a string.
String text = "Programming";
StringBuilder sb = new StringBuilder(text);
sb.reverse();
System.out.println(sb);Output:
gnimmargorPThis is much simpler than manually swapping characters.
Checking a Palindrome
A palindrome reads the same forward and backward.
Examples:
levelmadamradarJava example:
String text = "madam";
StringBuilder reversed = new StringBuilder(text);
reversed.reverse();
if (text.equals(reversed.toString())) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}Output:
PalindromeCounting Characters with StringBuilder
Although StringBuilder is mainly for modifying text, it can also be combined with loops for processing strings.
String text = "Java";
StringBuilder result = new StringBuilder();
for (int i = 0;
i < text.length();
i++) {
result.append(text.charAt(i));
}System.out.println(result);Output:
JavaRemoving Spaces
You can remove spaces while constructing a new string.
String text = "Java Programming Language";
StringBuilder result = new StringBuilder();
for (int i = 0;
i < text.length();
i++) {
char ch = text.charAt(i);
if (ch != ' ') {
result.append(ch);
}
}System.out.println(result);Output:
JavaProgrammingLanguageStringBuilder Example: Generate Numbers
public class Main {
public static void main(String[] args) {
StringBuilder numbers = new StringBuilder();
for (int i = 1;
i <= 20;
i++) {
numbers.append(i);
if (i < 20) {
numbers.append(", ");
}
} System.out.println(numbers);
}
}Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20This is a practical pattern for creating formatted lists.
Complete StringBuilder Example
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// Add text
sb.append("Java");
// Add more text
sb.append(" Programming");
// Insert text
sb.insert(5, "Language ");
System.out.println("After insert: " + sb);
// Replace text
sb.replace(0, 4, "Advanced Java");
System.out.println("After replace: " + sb);
// Delete characters
sb.delete(0, 9);
System.out.println("After delete: " + sb);
// Reverse
sb.reverse();
System.out.println("After reverse: " + sb);
// Convert to String
String result = sb.toString();
System.out.println("Final String: " + result);
}
}This example demonstrates the basic lifecycle of a StringBuilder: create it, append content, insert text, replace content, delete characters, reverse the sequence, and finally convert it to a String.
Important StringBuilder Methods
| Method | Purpose |
|---|---|
append() | Adds content at the end |
insert() | Adds content at a specific position |
delete() | Removes a range of characters |
deleteCharAt() | Removes one character |
replace() | Replaces characters in a range |
reverse() | Reverses the sequence |
charAt() | Returns a character |
setCharAt() | Changes a character |
length() | Returns current length |
capacity() | Returns current capacity |
ensureCapacity() | Ensures minimum capacity |
setLength() | Changes current length |
toString() | Converts builder to String |
Common StringBuilder Mistakes
1. Forgetting to Call toString()
If a method specifically requires a String, convert the builder:
String result = sb.toString();2. Using Invalid Indexes
This can cause an exception:
StringBuilder sb = new StringBuilder("Java");
sb.charAt(10);The valid indexes are only:
0 to 33. Confusing Length and Capacity
These are different:
sb.length();returns the number of characters currently stored.
sb.capacity();returns the current internal capacity.
4. Sharing One StringBuilder Between Threads
StringBuilder is not thread-safe.
Avoid using the same mutable builder from multiple threads without proper synchronization or another concurrency design.
5. Using StringBuilder Everywhere
You do not need StringBuilder for every string operation.
This is simple and readable:
String message = "Hello " + name;Use StringBuilder when repeated modification makes it useful.
Best Practices for StringBuilder
1. Use It for Repeated String Construction
StringBuilder sb = new StringBuilder();
for (int i = 0;
i < 1000;
i++) {
sb.append(i);
}2. Set an Appropriate Initial Capacity When Useful
If you know approximately how large the final text will be:
StringBuilder sb = new StringBuilder(1000);This can reduce the need for repeated internal growth.
3. Use Method Chaining Carefully
This is concise:
sb.append("Java") .append(" ") .append("Programming");But avoid overly long chains if they make the code difficult to understand.
4. Convert to String at the Boundary
When the final text is ready:
String result = sb.toString();5. Do Not Share Mutable Builders Unnecessarily
Keeping a StringBuilder local to the operation or thread that uses it makes the design easier to reason about.
StringBuilder: Quick Comparison
String↓Immutable↓Changes create new String valuesStringBuilder↓Mutable↓Modify the same builder↓append / insert / delete / replace / reverse↓toString()↓Final StringFrequently Asked Questions
What is StringBuilder in Java?
StringBuilder is a Java class used to create and modify a mutable sequence of characters efficiently.
Is StringBuilder mutable?
Yes. Its contents can be changed after the object is created.
Why is StringBuilder faster than String concatenation?
For repeated string modifications, StringBuilder can avoid creating a new immutable String for every modification and therefore can reduce unnecessary object creation.
Is StringBuilder thread-safe?
No. StringBuilder is not synchronized and should not be assumed to be thread-safe.
What is the difference between String and StringBuilder?
String is immutable, while StringBuilder is mutable.
What is the difference between StringBuilder and StringBuffer?
Both are mutable character sequences. StringBuffer provides synchronization, while StringBuilder does not.
How do I convert StringBuilder to String?
Use:
String result = sb.toString();Can StringBuilder store numbers?
Yes.
StringBuilder sb = new StringBuilder();
sb.append(100);
sb.append(25.5);Can StringBuilder reverse a string?
Yes.
sb.reverse();What does capacity() mean in StringBuilder?
capacity() returns the amount of internal character storage currently available before the builder needs to grow.
Should I always use StringBuilder instead of +?
No. For simple string concatenation, + is usually clearer. StringBuilder becomes especially useful for repeated or complex string construction.
Practice Questions
Beginner
What is
StringBuilderin Java?Is
StringBuildermutable or immutable?What does
append()do?How do you convert a
StringBuilderto aString?What does
reverse()do?What is the difference between
length()andcapacity()?
Intermediate
Write a program to reverse a string using
StringBuilder.Write a program to check whether a word is a palindrome.
Use
StringBuilderto generate numbers from 1 to 100.Use
insert()to add a word inside an existing sentence.Use
delete()to remove part of a sentence.Use
setCharAt()to change a character.
Advanced
Explain why
StringBuildercan be useful inside loops.Compare
String,StringBuilder, andStringBuffer.Explain why
StringBuilderis not thread-safe.Explain the difference between capacity and length.
Create a comma-separated list using
StringBuilderwithout leaving a trailing comma.
Quick Revision
Remember these important points:
StringBuilderis mutable.It belongs to the
java.langpackage.append()adds content at the end.insert()adds content at a particular index.delete()removes a range.deleteCharAt()removes one character.replace()replaces a range.reverse()reverses the content.setCharAt()changes an individual character.length()returns the current number of characters.capacity()returns the current internal capacity.toString()converts the builder into a normalString.StringBuilderis not thread-safe.It is particularly useful for repeated string construction.
Simple
+concatenation is still appropriate for many small expressions.
Graphic and Design Ideas
Graphic 1: String vs StringBuilder
Create a simple comparison diagram:
STRINGImmutable↓Modification↓New StringSTRINGBUILDERMutable↓Modification↓Same BuilderGraphic 2: StringBuilder Workflow
Create↓append()↓insert()↓replace()↓delete()↓reverse()↓toString()↓Final StringGraphic 3: Common Methods
Design a visual card containing:
append() insert()delete() replace()reverse() charAt()setCharAt() length()capacity() toString()Graphic 4: Performance Concept
Show:
String"Java" → "Java " → "Java Programming"↓Multiple String valuesStringBuilder"Java"↓append()"Java "↓append()"Java Programming"The visual should emphasize mutable text construction, not promise a fixed performance multiplier.
Runnable Code Example: Java StringBuilder
Java 17+public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" 21");
sb.append(" LTS");
sb.reverse();
System.out.println("Reversed string: " + sb.toString());
}
}