StringBuilder

A String cannot change, so every += in a loop creates a new string and copies all the old characters into it. A StringBuilder is a growable buffer that you edit in place and turn into a String once. This page explains how the buffer grows, measures the difference, runs every editing method, compares StringBuffer and the + operator, and shows the mistakes that compile but misbehave.

Contents

How StringBuilder works

A String is immutable: its characters are fixed when it is created. Building text piece by piece with s += x therefore creates a new string each time and copies everything built so far into it. After n appends, about n2/2 characters have been copied.

A StringBuilder holds a byte array that is larger than the text in it, plus a count of how much is used. Appending writes into the spare room. When the room runs out, the builder allocates a bigger array, roughly twice the size, and copies the text once. Because the size doubles, each character is copied only a few times on average, so building n characters costs time proportional to n.

Like String since Java 9, the builder stores Latin-1 text with one byte per character and switches to two bytes per character the first time a character outside Latin-1 is appended. toString() copies the used part into a new, exact-sized String, so later edits to the builder never affect strings already produced.

Ways to build strings
ToolSinceThread-safeBest for
StringBuilderJava 5NoBuilding text in loops and helper methods
StringBufferJava 1.0Yes, every method is synchronizedLegacy APIs that require it
+ in one expressionJava 1.0; invokedynamic since Java 9Not applicableCombining a few values in one statement
String.join, StringJoiner, Collectors.joiningJava 8Not applicableValues with a separator
String.repeatJava 11Not applicableOne string repeated
StringBuilder.repeatJava 21NoPadding and separators inside a builder

The programs were compiled and run on JDK 21, which StringBuilder.repeat needs.

Why += in a loop is slow

The program builds strings of 10,000, 20,000 and 40,000 digits both ways, doubling the size each time, so the growth rate of each approach shows directly. Only the quickest of three runs counts for each size.

Java
public class WhyBuilder {

    public static void main(String[] args) {
        for (int n : new int[] {10000, 20000, 40000}) {
            long concat = best(() -> {
                String s = "";
                for (int i = 0; i < n; i++) {
                    s += i % 10;                 // each += copies the whole string so far
                }
                return s.length();
            });
            long builder = best(() -> {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < n; i++) {
                    sb.append(i % 10);           // appends into a growing buffer
                }
                return sb.toString().length();
            });
            System.out.printf("n=%,6d   String += %7.1f ms   StringBuilder %5.2f ms%n",
                n, concat / 1e6, builder / 1e6);
        }

        // A single expression is fine: the compiler builds it in one step
        String name = "Ada";
        int age = 36;
        String line = "Name: " + name + ", age: " + age;
        System.out.println(line);
    }

    interface Work {
        int run();
    }

    // Best of 3 runs, in nanoseconds
    static long best(Work w) {
        long best = Long.MAX_VALUE;
        for (int r = 0; r < 3; r++) {
            long t0 = System.nanoTime();
            w.run();
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best;
    }
}

Output (2-CPU Linux machine, JDK 21; treat the times as rough):

Output
n=10,000   String +=     8.1 ms   StringBuilder  0.22 ms
n=20,000   String +=    33.1 ms   StringBuilder  0.33 ms
n=40,000   String +=   117.8 ms   StringBuilder  0.32 ms
Name: Ada, age: 36
  • Each doubling of n made += roughly three to four times slower, the signature of quadratic work: at 40,000 characters the loop copied about 800 million characters in total.
  • The StringBuilder times grew slowly and stayed far below a millisecond. At 40,000 characters it was several hundred times faster, and the gap keeps widening as n grows.
  • The last line is not a problem. A single expression such as "Name: " + name + ", age: " + age is compiled into one concatenation that sizes the result once. Only repeated += in a loop is slow.

Editing methods

A builder can be changed anywhere, not just at the end. The program starts from Hello World and applies each editing method in turn, so each line shows the effect of one call.

Java
public class EditMethods {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello World");

        sb.append('!').append(" Count: ").append(3).append(", ok=").append(true);
        System.out.println("append:      " + sb);

        sb.insert(0, ">> ");
        System.out.println("insert:      " + sb);

        sb.delete(0, 3);                       // [start, end)
        System.out.println("delete:      " + sb);

        sb.replace(6, 11, "Java");             // replaces the range [6, 11)
        System.out.println("replace:     " + sb);

        sb.setCharAt(0, 'J');
        sb.deleteCharAt(sb.indexOf("!"));
        System.out.println("setCharAt/deleteCharAt: " + sb);

        System.out.println("indexOf(\"Java\") = " + sb.indexOf("Java")
            + ", charAt(1) = " + sb.charAt(1) + ", substring(6, 10) = " + sb.substring(6, 10));

        sb.setLength(5);                       // truncate
        System.out.println("setLength(5): " + sb);
        sb.setLength(7);                       // extend with '\u0000' characters
        System.out.println("setLength(7): length " + sb.length() + ", last char code "
            + (int) sb.charAt(6));
        sb.setLength(0);                       // reuse: clear, keeping the capacity

        // Java 21: repeat, for padding and separators
        sb.append("id").repeat(' ', 6).append('|').repeat("-=", 3);
        System.out.println("repeat:      [" + sb + "]");

        // reverse keeps surrogate pairs together
        StringBuilder word = new StringBuilder("stressed");
        System.out.println("reverse:     " + word.reverse());
        String clef = new StringBuilder("ab\uD834\uDD1E").reverse().toString();
        System.out.println("reverse with U+1D11E: first code point U+"
            + Integer.toHexString(clef.codePointAt(0)).toUpperCase() + ", length " + clef.length());

        // Methods return the same builder, which is why calls chain
        StringBuilder same = sb.append("?");
        System.out.println("append returns this: " + (same == sb));
    }
}

Output:

Output
append:      Hello World! Count: 3, ok=true
insert:      >> Hello World! Count: 3, ok=true
delete:      Hello World! Count: 3, ok=true
replace:     Hello Java! Count: 3, ok=true
setCharAt/deleteCharAt: Jello Java Count: 3, ok=true
indexOf("Java") = 6, charAt(1) = e, substring(6, 10) = Java
setLength(5): Jello
setLength(7): length 7, last char code 0
repeat:      [id      |-=-=-=]
reverse:     desserts
reverse with U+1D11E: first code point U+1D11E, length 4
append returns this: true
  • append has overloads for every primitive, char[], CharSequence and Object, so numbers and booleans need no conversion.
  • insert(0, ...), delete(start, end) and replace(start, end, str) use the same half-open ranges as substring: replace(6, 11, "Java") replaced the five characters World. Inserting or deleting near the start moves all the following characters, so it costs time proportional to the length.
  • setCharAt changes one character in place and deleteCharAt removes one; here the exclamation mark, found with indexOf.
  • indexOf, charAt and substring work as on String.
  • setLength(5) truncates. Making it longer pads with '\u0000' characters, code 0, which are invisible but count. setLength(0) clears the builder for reuse and keeps its capacity.
  • repeat, new in Java 21, appends a character or a string a number of times: six spaces, then -= three times.
  • reverse() treats surrogate pairs as single characters, so the G clef U+1D11E stays intact and becomes the first code point.
  • Every editing method returns the same builder, which is what makes chained calls work.

Capacity and growth

The capacity is the size of the internal array, which is always at least the length. The program watches it grow while appending 1,000 characters one at a time, then shrinks and pre-sizes it.

Java
public class Capacity {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        System.out.println("new StringBuilder():       capacity " + sb.capacity());
        System.out.println("new StringBuilder(\"abc\"): capacity "
            + new StringBuilder("abc").capacity() + " (16 + length)");

        // Watch the buffer grow: each time the capacity is exceeded it becomes old * 2 + 2
        int last = sb.capacity();
        StringBuilder growth = new StringBuilder(String.valueOf(last));
        for (int i = 0; i < 1000; i++) {
            sb.append('x');
            if (sb.capacity() != last) {
                last = sb.capacity();
                growth.append(" -> ").append(last);
            }
        }
        System.out.println("growth while appending 1000 chars: " + growth);

        // A big append jumps straight to what is needed
        StringBuilder jump = new StringBuilder();
        jump.append("y".repeat(100));
        System.out.println("append of 100 chars to an empty builder: capacity " + jump.capacity());

        sb.setLength(10);
        System.out.println("after setLength(10): length " + sb.length() + ", capacity "
            + sb.capacity());
        sb.trimToSize();
        System.out.println("after trimToSize():  capacity " + sb.capacity());
        sb.ensureCapacity(500);
        System.out.println("after ensureCapacity(500): capacity " + sb.capacity());

        // Pre-sizing avoids the copies; measured on 2,000,000 appends
        System.out.printf("default size: %.1f ms, pre-sized: %.1f ms%n",
            best(false) / 1e6, best(true) / 1e6);
    }

    static long best(boolean presize) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            StringBuilder b = presize ? new StringBuilder(2000000) : new StringBuilder();
            for (int i = 0; i < 2000000; i++) {
                b.append('z');
            }
            if (b.length() != 2000000) {
                throw new AssertionError();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best;
    }
}

Output (the last line is a rough comparison, best of 3 runs):

Output
new StringBuilder():       capacity 16
new StringBuilder("abc"): capacity 19 (16 + length)
growth while appending 1000 chars: 16 -> 34 -> 70 -> 142 -> 286 -> 574 -> 1150
append of 100 chars to an empty builder: capacity 100
after setLength(10): length 10, capacity 1150
after trimToSize():  capacity 10
after ensureCapacity(500): capacity 500
default size: 4.5 ms, pre-sized: 2.7 ms
  • An empty builder starts with room for 16 characters, and one created from a string gets 16 more than the string's length, 19 for abc.
  • When it runs out, the new capacity is the old one times 2 plus 2: 16, 34, 70, 142 and so on. Seven arrays were allocated to hold 1,000 characters, and the final one has room for 1,150.
  • When a single append needs more than double, the builder grows straight to what is needed, so appending 100 characters to an empty builder gave capacity 100.
  • setLength never shrinks the array. trimToSize() does, and ensureCapacity(500) grows it in advance.
  • Pre-sizing a builder for 2 million characters avoided about 17 grow-and-copy steps and was noticeably faster. The saving is real but modest, because doubling already keeps copying cheap; pre-size when the final size is roughly known.

Mistakes that compile

Each of these compiles without a warning, which is why they survive code review. The program runs them all.

Java
import java.util.HashSet;
import java.util.Set;

public class Gotchas {

    public static void main(String[] args) {
        // 1. StringBuilder does not override equals or hashCode
        StringBuilder a = new StringBuilder("abc");
        StringBuilder b = new StringBuilder("abc");
        System.out.println("1. a.equals(b):              " + a.equals(b));
        System.out.println("   a.compareTo(b) == 0:      " + (a.compareTo(b) == 0));
        System.out.println("   a.toString().equals(...): " + a.toString().equals(b.toString()));
        System.out.println("   CharSequence.compare:     " + (CharSequence.compare(a, "abc") == 0));
        Set<StringBuilder> set = new HashSet<>();
        set.add(a);
        System.out.println("   set.contains(b):          " + set.contains(b));

        // 2. new StringBuilder('x') takes an int capacity, not a char
        StringBuilder fromChar = new StringBuilder('x');
        System.out.println("2. new StringBuilder('x'): [" + fromChar + "], capacity "
            + fromChar.capacity() + " ('x' is 120)");

        // 3. A builder used as a map key or kept after toString() can change later
        StringBuilder key = new StringBuilder("k1");
        String snapshot = key.toString();
        key.append("-changed");
        System.out.println("3. snapshot " + snapshot + ", builder now " + key);

        // 4. + inside append builds a temporary String first
        String first = "a";
        String second = "b";
        StringBuilder sb = new StringBuilder();
        sb.append(first).append(", ").append(second);    // not append(first + ", " + second)
        System.out.println("4. chained: " + sb);

        // 5. append(char[]) and append(Object) differ
        char[] letters = {'h', 'i'};
        Object asObject = letters;
        System.out.println("5. append(char[]): " + new StringBuilder().append(letters)
            + ", append(Object) starts with: "
            + new StringBuilder().append(asObject).substring(0, 2));

        // 6. Index errors throw, as with String
        try {
            new StringBuilder("abc").insert(5, "x");
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("6. insert(5, ...) on length 3: " + e.getMessage());
        }
    }
}

Output:

Output
1. a.equals(b):              false
   a.compareTo(b) == 0:      true
   a.toString().equals(...): true
   CharSequence.compare:     true
   set.contains(b):          false
2. new StringBuilder('x'): [], capacity 120 ('x' is 120)
3. snapshot k1, builder now k1-changed
4. chained: a, b
5. append(char[]): hi, append(Object) starts with: [C
6. insert(5, ...) on length 3: Range [5, 3) out of bounds for length 3
  1. StringBuilder inherits equals and hashCode from Object, so two builders with the same text are not equal and a HashSet cannot find one by the other. Compare with compareTo (Java 11), CharSequence.compare (Java 11), or toString().equals.
  2. There is no StringBuilder(char) constructor. 'x' is widened to the int 120 and taken as the capacity, so the builder is empty.
  3. A builder is mutable, so a value taken with toString() is a snapshot, while the builder itself keeps changing. Never use a builder as a map key or store it where a fixed value is expected.
  4. append(first + ", " + second) builds a temporary string before appending it. Chain the appends instead.
  5. append(char[]) appends the characters, but the same array typed as Object appends its toString(), something like [C@1b6d3586.
  6. Bad positions throw StringIndexOutOfBoundsException, as on String.

StringBuffer, concat and the + operator

StringBuffer is the original, synchronized version of the same class, and + is what most code uses. The program compares them in a loop, and then compares one + expression with the equivalent builder code, keeping the fastest of three runs for each.

Java
import java.util.function.IntFunction;

public class BuilderVsBuffer {

    public static void main(String[] args) {
        int n = 5000000;
        time("StringBuilder", n, count -> {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb.append('a').append(i % 10);
            }
            return sb.toString();
        });
        time("StringBuffer", n, count -> {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < count; i++) {
                sb.append('a').append(i % 10);
            }
            return sb.toString();
        });
        time("String.concat in loop", 20000, count -> {
            String s = "";
            for (int i = 0; i < count; i++) {
                s = s.concat("a").concat(String.valueOf(i % 10));
            }
            return s;
        });

        // One expression with + is compiled to a single invokedynamic call (Java 9+)
        time("one + expression x 1M", 1000000, count -> {
            String last = "";
            for (int i = 0; i < count; i++) {
                last = "id-" + i + "/" + (i % 7) + ":" + true;
            }
            return last;
        });
        time("StringBuilder x 1M", 1000000, count -> {
            String last = "";
            for (int i = 0; i < count; i++) {
                last = new StringBuilder().append("id-").append(i).append('/').append(i % 7)
                    .append(':').append(true).toString();
            }
            return last;
        });
    }

    // Best of 3 runs
    static void time(String name, int n, IntFunction<String> work) {
        long best = Long.MAX_VALUE;
        String result = "";
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            result = work.apply(n);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-24s n=%,10d %7.1f ms  length %,d%n", name, n, best / 1e6,
            result.length());
    }
}

Output (rough comparison on a 2-CPU Linux machine, JDK 21):

Output
StringBuilder            n= 5,000,000    32.9 ms  length 10,000,000
StringBuffer             n= 5,000,000    35.7 ms  length 10,000,000
String.concat in loop    n=    20,000   110.6 ms  length 40,000
one + expression x 1M    n= 1,000,000    15.5 ms  length 16
StringBuilder x 1M       n= 1,000,000    22.1 ms  length 16
  • StringBuffer was only slightly slower than StringBuilder. With no other thread involved, the JVM makes uncontended locks cheap. Its synchronization rarely helps anyway: two threads appending to one buffer still interleave their pieces in an unpredictable order. Use StringBuilder unless an API requires StringBuffer.
  • String.concat in a loop has the same quadratic cost as +=: 20,000 iterations took far longer than 5 million builder appends.
  • Since Java 9 (JEP 280), javac compiles a + expression into an invokedynamic call to StringConcatFactory, which computes the exact length and fills one array. In this run the single expression was faster than writing the same thing with a StringBuilder, which may have to grow its buffer.

So use + for single expressions and StringBuilder for loops. More comparisons are on the string performance page.

Patterns: separators, Appendable and reuse

Three situations come up again and again when builders are used in real code: putting a separator between items, writing a method that can output to a builder or to a file, and reusing one builder for many lines. The data is a small list of products.

Java
import java.io.IOException;
import java.util.List;
import java.util.StringJoiner;

public class BuildPatterns {

    record Product(String name, int stock) {
    }

    public static void main(String[] args) throws IOException {
        List<String> names = List.of("pen", "ink", "pad");

        // 1. Separator before every item except the first
        StringBuilder a = new StringBuilder();
        for (String n : names) {
            if (!a.isEmpty()) {
                a.append(", ");
            }
            a.append(n);
        }
        System.out.println("separator first:  " + a);

        // 2. Separator after every item, then cut the last one off
        StringBuilder b = new StringBuilder();
        for (String n : names) {
            b.append(n).append(", ");
        }
        b.setLength(b.length() - 2);
        System.out.println("cut last:         " + b);
        try {
            StringBuilder empty = new StringBuilder();
            empty.setLength(empty.length() - 2);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("cut last, empty:  " + e.getClass().getSimpleName());
        }

        // 3. StringJoiner handles the separator, and the empty case
        StringJoiner j = new StringJoiner(", ", "[", "]");
        names.forEach(j::add);
        System.out.println("StringJoiner:     " + j + ", empty: "
            + new StringJoiner(", ", "[", "]"));

        // Appendable: one method, many destinations
        List<Product> products = List.of(new Product("pen", 120), new Product("ink", 8));
        StringBuilder report = new StringBuilder();
        for (Product p : products) {
            writeRow(report, p);
        }
        System.out.print("into a builder:\n" + report);
        System.out.println("straight to System.out:");
        for (Product p : products) {
            writeRow(System.out, p);
        }

        // Reuse one builder for many lines
        StringBuilder line = new StringBuilder(64);
        for (int i = 1; i <= 3; i++) {
            line.setLength(0);
            line.append("line ").append(i).append(": ").repeat('*', i);
            System.out.println(line + "   capacity " + line.capacity());
        }
    }

    static void writeRow(Appendable out, Product p) throws IOException {
        out.append(p.name()).append(';').append(String.valueOf(p.stock())).append('\n');
    }
}

Output:

Output
separator first:  pen, ink, pad
cut last:         pen, ink, pad
cut last, empty:  StringIndexOutOfBoundsException
StringJoiner:     [pen, ink, pad], empty: []
into a builder:
pen;120
ink;8
straight to System.out:
pen;120
ink;8
line 1: *   capacity 64
line 2: **   capacity 64
line 3: ***   capacity 64
  • The trailing separator problem has three common fixes. Appending the separator before every item except the first avoids it. Appending after every item and then calling setLength(length - 2) removes it, but breaks on an empty list, where it would throw. A StringJoiner handles both cases without any special code.
  • A method that takes an Appendable works with StringBuilder, StringBuffer, any Writer and PrintStream. The same writeRow filled a builder and printed straight to System.out, without building a string first. Appendable methods declare IOException, which is why the method throws it.
  • Reusing a builder with setLength(0) keeps its grown array, so a loop that formats many lines allocates the buffer once. The capacity stayed the same for all three lines.

When to use StringBuilder

Choosing how to build a string
SituationUse
A few values in one statement+, or String.format for layout
Text built in a loop or across method callsStringBuilder
Values with a separatorString.join or Collectors.joining; see joining strings
Rough final size knownnew StringBuilder(expectedLength)
Padding or repeated separators in a buildersb.repeat(' ', n) (Java 21)
Reusing one buildersb.setLength(0)
Comparing contentsa.compareTo(b) == 0 or toString().equals
Shared between threadsBuild per thread, then combine; StringBuffer only for legacy APIs
Reversing textnew StringBuilder(s).reverse().toString()