Topic 77 of 119 7. Arrays and Strings in Java Interactive Tutorial

Java StringBuilder: Mutable String Operations for High Performance

9 mins read Last updated: 22 Aug 2026 28,321 views

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.

Main.java
Run Online
StringBuilder builder = new StringBuilder("Hello");
builder.append(" Java");
System.out.println(builder);

Output:

The same StringBuilder object can continue to be modified.

Main.java
Run Online
builder.append(" Programming");
System.out.println(builder);

Output:

Key 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:

Main.java
Run Online
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:

Main.java
Run Online
StringBuilder result = new StringBuilder();
for (int i = 1;
i <= 5;
i++) {
    result.append(i);
}System.out.println(result);

Output:

The 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.

FeatureStringStringBuilder
MutableNoYes
Can modify existing objectNoYes
String concatenationCan be expensive in repeated operationsGenerally efficient
Thread-safeImmutableNo
Performance for many modificationsUsually lowerUsually better
Packagejava.langjava.lang
Common useFixed textFrequently changing text

Example:

Main.java
Run Online
String text = "Hello";
text = text + " World";

A new String value is created.

With StringBuilder:

Main.java
Run Online
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

Main.java
Run Online
StringBuilder sb = new StringBuilder();

This creates an empty builder.

You can add content later:


2. StringBuilder with Initial Text

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello");

Now the builder contains:

You can modify it:

Main.java
Run Online
sb.append(" Java");
System.out.println(sb);

Output:


3. StringBuilder with Initial Capacity

You can also specify the initial capacity.

Main.java
Run Online
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.

Main.java
Run Online
StringBuilder sb = new StringBuilder(100);
System.out.println(sb.length());
System.out.println(sb.capacity());

The length starts at:

while the capacity is:


append() Method

The append() method is one of the most commonly used StringBuilder methods.

It adds content to the end of the existing sequence.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
System.out.println(sb);

Output:

You can append different data types.

Main.java
Run Online
StringBuilder sb = new StringBuilder();
sb.append("Age: ");
sb.append(35);
sb.append(", Salary: ");
sb.append(44000.50);
System.out.println(sb);

Output:


Appending Characters

You can append individual characters.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");
sb.append('!');
System.out.println(sb);

Output:


Appending Boolean Values

Main.java
Run Online
StringBuilder sb = new StringBuilder();
sb.append("Java is popular: ");
sb.append(true);
System.out.println(sb);

Output:


Appending Arrays

You can also append arrays.

Main.java
Run Online
char[] letters = {
    'J', 'a', 'v', 'a'
};
StringBuilder sb = new StringBuilder();
sb.append(letters);
System.out.println(sb);

Output:


insert() Method

The insert() method adds content at a specified position.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(6, "Java ");
System.out.println(sb);

Output:

The index determines where the new content is inserted.


Inserting a Character

Main.java
Run Online
StringBuilder sb = new StringBuilder("Jva");
sb.insert(1, 'a');
System.out.println(sb);

Output:


Inserting Numbers

Main.java
Run Online
StringBuilder sb = new StringBuilder("Value: ");
sb.insert(7, 100);
System.out.println(sb);

Output:


delete() Method

The delete() method removes characters between two indexes.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello Java");
sb.delete(5, 10);
System.out.println(sb);

Output:

The starting index is included, while the ending index is excluded.

For:

characters from start through end - 1 are removed.


deleteCharAt() Method

If you want to remove a single character, use deleteCharAt().

Main.java
Run Online
StringBuilder sb = new StringBuilder("Jvaa");
sb.deleteCharAt(2);
System.out.println(sb);

Output:

Another example:

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");
sb.deleteCharAt(3);
System.out.println(sb);

Output:


replace() Method

The replace() method replaces a range of characters.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);

Output:

The syntax is:

Main.java
Run Online
replace(start, end, newText)

reverse() Method

The reverse() method reverses the contents of a StringBuilder.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);

Output:

This method is useful for simple palindrome programs and reverse-string operations.


Reverse a String Using StringBuilder

Main.java
Run Online
String text = "level";
StringBuilder sb = new StringBuilder(text);
sb.reverse();
System.out.println(sb);

Output:

You can compare the original and reversed values to check for a palindrome.


charAt() Method

charAt() returns the character at a specific index.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");
char ch = sb.charAt(2);
System.out.println(ch);

Output:

Indexes start at 0.

For:

the indexes are:

Main.java
Run Online
J → 0a → 1v → 2a → 3

setCharAt() Method

Unlike String, a StringBuilder allows you to directly change a character using setCharAt().

Main.java
Run Online
StringBuilder sb = new StringBuilder("Jova");
sb.setCharAt(1, 'a');
System.out.println(sb);

Output:

This is a good example of the mutability of StringBuilder.


length() Method

The length() method returns the number of characters currently stored.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.length());

Output:

After modification:

Main.java
Run Online
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.

Main.java
Run Online
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());

The default initial capacity is commonly 16.

You can specify a different initial capacity:

Main.java
Run Online
StringBuilder sb = new StringBuilder(100);
System.out.println(sb.capacity());

Output:

Capacity vs Length

These two concepts are different.

Main.java
Run Online
StringBuilder sb = new StringBuilder(50);
sb.append("Java");
System.out.println("Length: " + sb.length());
System.out.println("Capacity: " + sb.capacity());

Possible output:

The 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.

Main.java
Run Online
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.

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello");
sb.setLength(3);
System.out.println(sb);

Output:

If 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.

Main.java
Run Online
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" Java");
String result = sb.toString();
System.out.println(result);

Output:

This 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:

Main.java
Run Online
StringBuilder sb = new StringBuilder();
for (int i = 1;
i <= 10;
i++) {
    sb.append(i).append(" ");
}System.out.println(sb);

Output:

This 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.

Main.java
Run Online
StringBuilder sb = new StringBuilder();
sb.append("Java") .append(" ") .append("Programming") .append(" ") .append("Language");
System.out.println(sb);

Output:

Main.java
Run Online
Java Programming Language

Method chaining can make string-building code shorter and easier to read.


Building a Sentence

Main.java
Run Online
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:

Main.java
Run Online
Java is a powerful programming language.

Removing Extra Characters

StringBuilder can be useful when building comma-separated data.

Main.java
Run Online
StringBuilder sb = new StringBuilder();
sb.append("Java, ");
sb.append("Python, ");
sb.append("PHP, ");
System.out.println(sb);

Output:

You could remove the final comma and space:

Main.java
Run Online
sb.delete(sb.length() - 2, sb.length());
System.out.println(sb);

Output:


StringBuilder for CSV Data

A simple CSV-like string can be constructed efficiently.

Main.java
Run Online
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:

Main.java
Run Online
Name,Age,CityRahul,30,KolkataAmit,28,Delhi

This approach is useful when generating text output dynamically.


StringBuilder for HTML Generation

StringBuilder can also be useful for generating HTML text.

Main.java
Run Online
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:

Main.java
Run Online
StringBuilder query = new StringBuilder();
query.append("SELECT ");
query.append("name ");
query.append("FROM users ");
query.append("WHERE age > 18");
System.out.println(query);

Output:

Main.java
Run Online
SELECT name FROM users WHERE age > 18

In 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:

Main.java
Run Online
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:

Main.java
Run Online
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:

Main.java
Run Online
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:

Main.java
Run Online
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:

Main.java
Run Online
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.

FeatureStringBuilderStringBuffer
MutableYesYes
Thread-safeNoYes, through synchronization
SynchronizationNoYes
Typical single-thread performanceGenerally betterGenerally lower due to synchronization overhead
Common useSingle-threaded string constructionCases requiring its synchronization behavior

Example:

Main.java
Run Online
StringBuilder sb = new StringBuilder("Hello");

and:

Main.java
Run Online
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:

The literal "Java" can use the Java String Pool.

But:

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");

creates a mutable StringBuilder object containing the characters from "Java".

When you call:

Main.java
Run Online
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.

Main.java
Run Online
String text = "Hello Java";
StringBuilder sb = new StringBuilder(text);
sb.append(" Programming");
System.out.println(sb);

Output:


Converting StringBuilder to String

Use toString().

Main.java
Run Online
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.

Main.java
Run Online
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.

Main.java
Run Online
String text = "Programming";
StringBuilder sb = new StringBuilder(text);
sb.reverse();
System.out.println(sb);

Output:

This is much simpler than manually swapping characters.


Checking a Palindrome

A palindrome reads the same forward and backward.

Examples:

Java example:

Main.java
Run Online
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:


Counting Characters with StringBuilder

Although StringBuilder is mainly for modifying text, it can also be combined with loops for processing strings.

Main.java
Run Online
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:


Removing Spaces

You can remove spaces while constructing a new string.

Main.java
Run Online
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:


StringBuilder Example: Generate Numbers

Main.java
Run Online
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:

Main.java
Run Online
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20

This is a practical pattern for creating formatted lists.


Complete StringBuilder Example

Main.java
Run Online
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

MethodPurpose
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:

Main.java
Run Online
String result = sb.toString();

2. Using Invalid Indexes

This can cause an exception:

Main.java
Run Online
StringBuilder sb = new StringBuilder("Java");
sb.charAt(10);

The valid indexes are only:


3. Confusing Length and Capacity

These are different:

returns the number of characters currently stored.

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:

Main.java
Run Online
String message = "Hello " + name;

Use StringBuilder when repeated modification makes it useful.


Best Practices for StringBuilder

1. Use It for Repeated String Construction

Main.java
Run Online
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:

Main.java
Run Online
StringBuilder sb = new StringBuilder(1000);

This can reduce the need for repeated internal growth.

3. Use Method Chaining Carefully

This is concise:

Main.java
Run Online
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:

Main.java
Run Online
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

Main.java
Run Online
String↓Immutable↓Changes create new String valuesStringBuilder↓Mutable↓Modify the same builder↓append / insert / delete / replace / reverse↓toString()↓Final String

Frequently 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:

Main.java
Run Online
String result = sb.toString();

Can StringBuilder store numbers?

Yes.

Main.java
Run Online
StringBuilder sb = new StringBuilder();
sb.append(100);
sb.append(25.5);

Can StringBuilder reverse a string?

Yes.

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

  1. What is StringBuilder in Java?

  2. Is StringBuilder mutable or immutable?

  3. What does append() do?

  4. How do you convert a StringBuilder to a String?

  5. What does reverse() do?

  6. What is the difference between length() and capacity()?

Intermediate

  1. Write a program to reverse a string using StringBuilder.

  2. Write a program to check whether a word is a palindrome.

  3. Use StringBuilder to generate numbers from 1 to 100.

  4. Use insert() to add a word inside an existing sentence.

  5. Use delete() to remove part of a sentence.

  6. Use setCharAt() to change a character.

Advanced

  1. Explain why StringBuilder can be useful inside loops.

  2. Compare String, StringBuilder, and StringBuffer.

  3. Explain why StringBuilder is not thread-safe.

  4. Explain the difference between capacity and length.

  5. Create a comma-separated list using StringBuilder without leaving a trailing comma.


Quick Revision

Remember these important points:

  • StringBuilder is mutable.

  • It belongs to the java.lang package.

  • 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 normal String.

  • StringBuilder is 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:

Main.java
Run Online
STRINGImmutable↓Modification↓New StringSTRINGBUILDERMutable↓Modification↓Same Builder

Graphic 2: StringBuilder Workflow

Main.java
Run Online
Create↓append()↓insert()↓replace()↓delete()↓reverse()↓toString()↓Final String

Graphic 3: Common Methods

Design a visual card containing:

Main.java
Run Online
append() insert()delete() replace()reverse() charAt()setCharAt() length()capacity() toString()

Graphic 4: Performance Concept

Show:

Main.java
Run Online
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+
Main.java
Run Online
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());
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

Why should you use StringBuilder instead of String concatenation in a loop?

String concatenation in a loop creates a new String object on every iteration (O(N^2) complexity and high GC overhead), while StringBuilder appends in place (O(N) amortized).
Q2

What is the default initial capacity of a StringBuilder?

16 characters (or 16 + length of initial string if initialized with a string).

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Use StringBuilder for string manipulation inside loops, methods, and algorithmic string building.