01 / 20

StringBuilder
in Java

Learn how to use StringBuilder for efficient string concatenation, understand mutable vs. immutable objects, and write faster Java code.

Java

The Problem with String Concatenation

In Java, String objects are immutable: once created, they cannot be changed. Every time you concatenate strings with +, Java creates a brand-new String object in memory and copies the old data into it.

String result = "";
for (int i = 0; i < 1000; i++) {
    result = result + "x"; // creates a new String every iteration!
}

Immutable vs. Mutable

String (Immutable)
Cannot be modified after creation. Every change creates a new object in memory. Safe for sharing between threads.
StringBuilder (Mutable)
Can be modified in place. Appending, inserting, or deleting characters changes the same internal buffer without creating new objects.

How Memory Differs

String + Concatenation "Hi" + "!" "Hi!" + " Java" "Hi! Java" garbage garbage 3 objects created StringBuilder Internal buffer (capacity 16) H i .append("!") H i ! .append(" Java") H i ! J a v a 1 object, same buffer reused

What Is StringBuilder?

StringBuilder is a class in java.lang that represents a mutable sequence of characters. It provides methods to append, insert, delete, and reverse characters without creating new objects.

Package
java.lang (auto-imported)
Default Capacity
16 characters initially
Thread Safety
Not synchronized (use StringBuffer if needed)

Core API Methods

Method Returns Description
append(x) StringBuilder Adds x to the end
insert(i, x) StringBuilder Inserts x at index i
delete(s, e) StringBuilder Removes chars from s to e (exclusive)
reverse() StringBuilder Reverses the sequence
toString() String Converts to immutable String
length() int Current number of characters

String vs. StringBuilder vs. StringBuffer

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread Safe? Yes (immutable) No Yes (synchronized)
Performance Slow (concat) Fastest Moderate
Use When Few changes Many changes, single thread Many changes, multi-thread

How to Apply StringBuilder

1
Create a StringBuilder. Use new StringBuilder() or new StringBuilder(initialCapacity) if you know the approximate size.
2
Append content in a loop. Call .append() for each piece of data: strings, numbers, characters, or even other objects.
3
Chain methods if needed. Use .insert(), .delete(), or .reverse() to manipulate the buffer further.
4
Convert to String. Call .toString() when you need the final immutable result.

Example 1: Basic Usage

Java
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");

String result = sb.toString();
// result: "Hello World"

Example 2: Method Chaining

Java
String csv = new StringBuilder()
    .append("Name")
    .append(",")
    .append("Age")
    .append(",")
    .append("Grade")
    .toString();

// csv: "Name,Age,Grade"

Example 3: Loop with StringBuilder

Java
String[] words = {"Java", "is", "fast"};
StringBuilder sb = new StringBuilder();

for (int i = 0; i < words.length; i++) {
    sb.append(words[i]);
    if (i < words.length - 1) {
        sb.append(" ");
    }
}

String sentence = sb.toString();
// sentence: "Java is fast"

Performance at Scale

Time (ms) Number of concatenations (n) 0 10k 50k 100k 200k 0 500 1000 1500 2000 String + StringBuilder
String + ~\(O(n^2)\)
StringBuilder ~\(O(n)\)

insert, delete, and reverse

Java
StringBuilder sb = new StringBuilder("Hello World");

// Insert at index 5
sb.insert(5, ",");
// "Hello, World"

// Delete index 5 to 7 (removes ", ")
sb.delete(5, 7);
// "HelloWorld"

// Reverse the entire string
sb.reverse();
// "dlroWolleH"

Capacity vs. Length

J a v a ... ... length() = 4 capacity() = 16
length()
Number of characters currently stored. Changes with every append, insert, or delete.
capacity()
Total size of the internal buffer. Grows automatically when length exceeds capacity.

Common Mistakes

✕ Assuming append() returns String
The append() method returns the StringBuilder itself (for chaining), not a String. A common error is trying to assign its result to a String variable, which causes a compile error.
✕ Using + inside a loop
Writing result = result + str in a loop creates a new String each time. This is the exact problem StringBuilder solves.
✕ Forgetting .toString()
Passing a StringBuilder where a String is expected may work (via implicit toString), but calling .toString() explicitly is clearer and safer.

Question 1 of 5

Why is StringBuilder more efficient than using the + operator for string concatenation inside a loop?

Question 2 of 5

What is the default initial capacity of a StringBuilder created with new StringBuilder()?

Question 3 of 5

What does the following code print?

StringBuilder sb = new StringBuilder("ABCDE");
sb.delete(1, 3);
System.out.println(sb);

Question 4 of 5

Which method converts a StringBuilder into an immutable String?

Question 5 of 5

What is the output of the following code?

StringBuilder sb = new StringBuilder("Java");
sb.insert(4, "Script");
sb.reverse();
System.out.println(sb.length());