Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 201 ยท Strings

StringBuilder

Learn Java's StringBuilder - why += in a loop is slow, how append, insert, delete, replace and reverse work, capacity, chaining and the pitfalls to avoid.

A Java String can never change. Every method that seems to modify one, such as concat, replace or toUpperCase, actually builds a brand-new string and leaves the original alone. That is great for safety, but it becomes a problem when you assemble text piece by piece: each step copies everything built so far.

StringBuilder is the fix. It is a mutable sequence of characters: you add, insert, delete and replace characters in place, and only turn the result into a String when you are done. In this lesson you'll see why it is faster, learn every method you'll use day to day, and pick up the pitfalls that catch even experienced developers.

Why += in a loop is slow

Recall from Strings that strings are immutable. So what does this code actually do?

Java
String result = "";
for (int i = 0; i < 5; i++) {
    result += i;   // result = result + i
}

Each += creates a new String that contains a copy of all the old characters plus the new ones. The old string becomes garbage. With 5 iterations nobody notices. With 50,000 iterations, the program copies the growing text 50,000 times, so the total work grows with the square of the length. Doubling the input roughly quadruples the time.

A StringBuilder keeps an internal character buffer with spare room. Appending usually just writes new characters into that spare room. When the buffer fills up, it grows to roughly double its size, so the occasional copy is cheap on average. The total work grows linearly with the length.

Run this comparison. The exact numbers depend on the machine, but the gap is always large:

Java String += versus StringBuilder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try changing count to 40_000: the += time grows several times over, while the StringBuilder time barely moves.

A single expression such as "Hello, " + name + "!" is not a problem. The compiler turns one expression into one efficient concatenation (since Java 9 it uses a special bootstrap method, StringConcatFactory). Reach for StringBuilder when you build a string across many statements, usually in a loop.

Creating a StringBuilder

There are three constructors you'll use:

Java
var empty = new StringBuilder();            // empty, room for 16 chars
var sized = new StringBuilder(1_000);       // empty, room for 1,000 chars
var copy  = new StringBuilder("Draft: ");   // starts with this text

StringBuilder lives in java.lang, so no import is needed. Calling toString() gives you an ordinary, immutable String snapshot. Later changes to the builder don't affect strings you already took out of it.

Adding text with append

append adds to the end. It is overloaded for every primitive type, char[], CharSequence (including other builders) and Object (it calls String.valueOf, so null becomes the text "null"):

Java append works with every type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

IO.println(line) works without toString() because println calls toString() on any object for you.

Method chaining

Most StringBuilder methods return the same builder (this), so you can chain calls into one readable statement. This is called a fluent API:

Java
String csvRow = new StringBuilder()
        .append("Ada").append(',')
        .append(36).append(',')
        .append("London")
        .toString();   // "Ada,36,London"

Chaining doesn't create new objects; every call changes the same builder.

Changing the content in place

Positions in a StringBuilder work like String indexes: the first character is at index 0, and ranges are start inclusive, end exclusive, just like substring.

Method What it does
insert(index, value) Inserts value before the character at index (index == length() appends).
delete(start, end) Removes characters from start up to, but not including, end.
deleteCharAt(index) Removes one character.
replace(start, end, str) Replaces the range with str (which can be longer or shorter).
setCharAt(index, ch) Overwrites one character.
reverse() Reverses the sequence.
setLength(n) Cuts the content to n characters, or pads with '\u0000' if longer.
Java insert, delete, replace, setCharAt and reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

setLength(0) is the fastest way to reuse a builder inside a loop: it clears the content but keeps the already-allocated buffer.

Passing an index outside the content throws StringIndexOutOfBoundsException. For example, new StringBuilder("abc").insert(4, "x") fails because the largest valid insert position is 3 (the length).

Reading from a builder

A builder also has many read methods that mirror String: charAt, length, indexOf, lastIndexOf, substring, chars() and isEmpty() (Java 15+). Use them to inspect the content without converting it first.

Checking for palindromes with reverse

reverse() is the classic way to reverse text in Java, because String itself has no reverse method. Here it powers a palindrome checker that ignores case, spaces and punctuation:

Java Palindrome checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the order: we take forward before calling reverse(), because reverse() changes the builder itself. Swap those two lines and both strings would be reversed.

reverse() is also Unicode-aware: it keeps surrogate pairs (such as most emoji) together instead of splitting them into broken halves.

Capacity and growth

A builder has two sizes:

  • length: how many characters it currently holds.
  • capacity: how many characters fit in the internal buffer before it must grow.

The empty constructor starts with capacity 16. new StringBuilder("text") starts with the text's length plus 16. When an append doesn't fit, the buffer grows to about twice its old size plus 2 (or more if a single append needs more), and the content is copied once.

Java Watching the capacity grow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When you know roughly how big the result will be, pass that size to the constructor (or call ensureCapacity) to skip the intermediate copies. It is a small win; don't obsess over it. trimToSize() shrinks the buffer to fit the content, which is rarely needed because the builder is usually thrown away right after toString().

Pitfalls professionals know

StringBuilder doesn't override equals

This surprises nearly everyone once. StringBuilder inherits equals and hashCode from Object, so two builders with the same text are not equal:

Java Comparing builders correctly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compare the content with compareTo (Java 11+), String.contentEquals, or by converting both with toString(). For the same reason, never use a StringBuilder as a HashMap key or put it in a HashSet: its hash code is based on identity, and its content can change anyway.

Don't mix + into append

This defeats the purpose, because the + builds a temporary string first:

Java
sb.append("Name: " + name + "\n");          // creates a temporary String
sb.append("Name: ").append(name).append('\n'); // appends directly

For a single short line the difference is tiny, but inside a hot loop prefer the chained form. For fixed templates, String.formatted (see Formatting Strings) is often the most readable choice.

It isn't thread-safe

StringBuilder has no internal locking. If two threads append to the same builder at the same time, the content can be corrupted. That is almost never a real problem, because builders are usually local variables inside a single method. The older StringBuffer class is the synchronized version; the next lesson explains when (rarely) you need it.

Builders are for building, strings are for sharing

Return a String, not a StringBuilder, from your methods. A String can't be changed by the caller, can be used as a map key and compares with equals as expected. Keep the builder as a private detail of the method that builds the text.

A practical example: building a table

Here is a typical real-world use: generating a text report row by row, with a builder reused for each line via setLength(0):

Java Building a small report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compact source file imports java.util automatically (through java.base), which is why List works without an import here.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? var sb = new StringBuilder("abc"); sb.append("d").reverse(); IO.println(sb);

    append adds "d" to get "abcd", and reverse changes the same builder in place, so it prints "dcba".
  2. 2. Why is result += word inside a loop of 100,000 iterations slow?

    Strings are immutable, so each += copies the whole text built so far into a new String. The total work grows with the square of the length.
  3. 3. What does new StringBuilder("same").equals(new StringBuilder("same")) return?

    StringBuilder does not override equals, so it compares identity. Use compareTo, contentEquals or toString().equals to compare content.
  4. 4. Given var sb = new StringBuilder("Hello World");, what does sb.delete(0, 6) leave?

    The range is start inclusive, end exclusive, so indexes 0 to 5 ("Hello" plus the space) are removed, leaving "World".
  5. 5. Which statement about StringBuilder is true?

    Methods like append, insert and reverse return this, enabling chaining. StringBuilder is not synchronized, toString() returns an independent String, and capacity is usually larger than length.

Summary

  • String is immutable; building text with += across many statements copies it again and again.
  • StringBuilder is a mutable character buffer: append, insert, delete, deleteCharAt, replace, setCharAt, reverse and setLength change it in place.
  • Most methods return the builder itself, so you can chain calls; toString() produces an independent String.
  • Ranges are start inclusive, end exclusive; invalid indexes throw StringIndexOutOfBoundsException.
  • Capacity starts at 16 (or text length + 16) and roughly doubles when needed; presize it when you know the final size.
  • StringBuilder doesn't override equals/hashCode and isn't thread-safe; return String from your methods.

Next: StringBuffer, StringJoiner and StringTokenizer, where you'll meet the thread-safe builder and easy ways to join and split text.