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 Strings += x
A StringBuilder
Like StringtoString()String
| Tool | Since | Thread-safe | Best for |
|---|---|---|---|
StringBuilder | Java 5 | No | Building text in loops and helper methods |
StringBuffer | Java 1.0 | Yes, every method is synchronized | Legacy APIs that require it |
+ | Java 1.0; invokedynamic | Not applicable | Combining a few values in one statement |
String.joinStringJoinerCollectors.joining | Java 8 | Not applicable | Values with a separator |
String.repeat | Java 11 | Not applicable | One string repeated |
StringBuilder.repeat | Java 21 | No | Padding and separators inside a builder |
The programs were compiled and run on JDK 21, which StringBuilder.repeat
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.
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):
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
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.StringBuilder - The last line is not a problem. A single expression such as
is compiled into one concatenation that sizes the result once. Only repeated"Name: " + name + ", age: " + age in a loop is slow.+=
Editing methods
A builder can be changed anywhere, not just at the end. The program starts from Hello World
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:
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
has overloads for every primitive,append ,char[] andCharSequence , so numbers and booleans need no conversion.Object ,insert(0, ...) anddelete(start, end) use the same half-open ranges asreplace(start, end, str) :substring replaced the five charactersreplace(6, 11, "Java") . Inserting or deleting near the start moves all the following characters, so it costs time proportional to the length.World changes one character in place andsetCharAt removes one; here the exclamation mark, found withdeleteCharAt .indexOf ,indexOf andcharAt work as onsubstring .String truncates. Making it longer pads withsetLength(5) characters, code 0, which are invisible but count.'\u0000' clears the builder for reuse and keeps its capacity.setLength(0) , new in Java 21, appends a character or a string a number of times: six spaces, thenrepeat three times.-= treats surrogate pairs as single characters, so the G clef U+1D11E stays intact and becomes the first code point.reverse()- 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.
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):
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.
never shrinks the array.setLength does, andtrimToSize() grows it in advance.ensureCapacity(500)- 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.
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:
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
inheritsStringBuilder andequals fromhashCode , so two builders with the same text are not equal and aObject cannot find one by the other. Compare withHashSet (Java 11),compareTo (Java 11), orCharSequence.compare .toString().equals- There is no
constructor.StringBuilder(char) is widened to the'x' 120 and taken as the capacity, so the builder is empty.int - A builder is mutable, so a value taken with
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.toString() builds a temporary string before appending it. Chain the appends instead.append(first + ", " + second) appends the characters, but the same array typed asappend(char[]) appends itsObject , something liketoString() .[C@1b6d3586- Bad positions throw
, as onStringIndexOutOfBoundsException .String
StringBuffer, concat and the + operator
StringBuffer++
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):
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
was only slightly slower thanStringBuffer . 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. UseStringBuilder unless an API requiresStringBuilder .StringBuffer in a loop has the same quadratic cost asString.concat : 20,000 iterations took far longer than 5 million builder appends.+=- Since Java 9 (JEP 280),
compiles ajavac expression into an+ call toinvokedynamic , which computes the exact length and fills one array. In this run the single expression was faster than writing the same thing with aStringConcatFactory , which may have to grow its buffer.StringBuilder
So use +StringBuilder
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.
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:
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
removes it, but breaks on an empty list, where it would throw. AsetLength(length - 2) handles both cases without any special code.StringJoiner - A method that takes an
works withAppendable ,StringBuilder , anyStringBuffer andWriter . The samePrintStream filled a builder and printed straight towriteRow , without building a string first.System.out methods declareAppendable , which is why the method throws it.IOException - Reusing a builder with
keeps its grown array, so a loop that formats many lines allocates the buffer once. The capacity stayed the same for all three lines.setLength(0)
When to use StringBuilder
| Situation | Use |
|---|---|
| A few values in one statement | +String.format |
| Text built in a loop or across method calls | StringBuilder |
| Values with a separator | String.joinCollectors.joining |
| Rough final size known | new StringBuilder(expectedLength) |
| Padding or repeated separators in a builder | sb.repeat(' ', n) |
| Reusing one builder | sb.setLength(0) |
| Comparing contents | a.compareTo(b) == 0toString().equals |
| Shared between threads | Build per thread, then combine; StringBuffer |
| Reversing text | new StringBuilder(s).reverse().toString() |