StringBuilder
A String cannot change, and a program that builds text piece by piece needs something that can. StringBuilder is that class: a growable buffer of characters with methods that change it in place, and one toString at the end to freeze the result into a string.
StringBuilder
The buffer starts empty or with a string, grows as needed and answers the methods of the moment: append adds at the end, insert adds at an index, replace swaps a range, delete removes one and reverse flips the whole buffer. Every one of them returns the builder itself, which is what makes a chain of calls possible.
The file Builder.java:
public class Builder {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Java");
builder.append(" 21");
builder.insert(0, "> ");
builder.replace(6, 8, "!");
System.out.println(builder.toString());
builder.reverse();
System.out.println(builder.toString());
System.out.println("length: " + builder.length());
}
}
javac -Xlint:all Builder.java
java Builder
> Java!1
1!avaJ >
length: 8
append made Java 21, insert put the arrow in front, and replace(6, 8, "!") replaced the two characters at 6 and 7, which were the space and the 2, with one character. The length is 8, and the reverse shows the arrow now at the end.
Building a string in a loop
A separator between elements is the classic loop: append the separator only when there is an element before, then append the element. With a builder the loop allocates one buffer, and with += it allocates a new string on every pass.
public class Loop {
public static void main(String[] args) {
String[] names = {"Ada", "Grace", "Alan"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < names.length; i++) {
if (i > 0) {
builder.append(", ");
}
builder.append(names[i]);
}
System.out.println(builder);
String joined = "";
for (String name : names) {
joined += name + ";";
}
System.out.println(joined);
}
}
javac -Xlint:all Loop.java
java Loop
Ada, Grace, Alan
Ada;Grace;Alan;
The second loop shows the other style, with its trailing separator at the end. Both give the same text for three names, and the difference appears when the list is long: the builder copies the existing characters only when it grows its buffer, while += creates a new string of the whole current length on every pass.
Why + in a loop is slow
Since Java 9 the compiler turns one concatenation into an invokedynamic call, but that is still a new string: the old characters are copied into it. In a loop of n passes the total copied is proportional to n squared, which is why a builder is the standard advice for text built in a loop.
public class Quadratic {
public static void main(String[] args) {
int n = 1000;
String text = "";
for (int i = 0; i < n; i++) {
text += "x";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n; i++) {
builder.append("x");
}
System.out.println("string: " + text.length());
System.out.println("builder: " + builder.length());
System.out.println("equal: " + text.equals(builder.toString()));
}
}
javac -Xlint:all Quadratic.java
java Quadratic
string: 1000
builder: 1000
equal: true
The two results are equal, as they must be. The comparison of their cost is not visible in the output, and the page does not invent a timing: the difference is in the number of allocations, which a profiler shows and the code explains. For a few concatenations in one expression the compiler handles it fine; the rule is about loops.
Exercises
- Build the string 1, 2, 3, 4, 5 with a builder and one loop.
- Use insert and delete to turn abcdef into abXef.
- Reverse a string with a builder in one call, then with a loop that appends characters from the end.
- Change n in Quadratic.java to 10000 and run both versions again. Does the output change?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
StringBuilder.appendreturn?Answer
The same builder, so calls can be chained
The builder returns itself, which is what makes builder.append(a).append(b) work.
-
What is the advantage of a StringBuilder over
+=in a loop?Answer
It changes one buffer instead of creating a new string every pass
Each += copies the whole current string, so the work grows with the square of the length.
-
Which method turns a StringBuilder back into a String?
Answer
toString
toString returns a String with the current contents of the buffer.
-
What does this program print?
public class Q1 { public static void main(String[] args) { StringBuilder builder = new StringBuilder("ab"); builder.append("cd").insert(0, ">"); System.out.println(builder); } }Answer
>abcd
append gives abcd and insert puts the arrow at index 0.
-
What does this program print?
public class Q2 { public static void main(String[] args) { StringBuilder builder = new StringBuilder("abc"); builder.reverse(); System.out.println(builder + " " + builder.length()); } }Answer
cba 3
reverse flips the buffer in place, and its length does not change.
-
What does this program print?
public class Q3 { public static void main(String[] args) { String text = "Java"; text.toUpperCase(); System.out.println(text); } }Answer
Java
toUpperCase returns a new string and the result is discarded; the original stays Java.
-
What does this program print?
public class Q4 { public static void main(String[] args) { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= 3; i++) { builder.append(i); } System.out.println(builder.toString()); } }Answer
123
Each pass appends the number as text, so the buffer holds 123.
-
What does
builder.replace(6, 8, "!")do to> Java 21?Answer
Replaces the characters at indices 6 and 7 with one character
The end index is exclusive, so the two characters at 6 and 7 become the one replacement.
-
What does a StringBuilder start with when it is created with no argument?
Answer
An empty buffer of length 0
The no-argument constructor creates an empty builder, which is why append starts from nothing.
-
What does this program print?
public class Q5 { public static void main(String[] args) { StringBuilder builder = new StringBuilder("x"); builder.append("y"); System.out.println(builder.length()); } }Answer
2
The buffer holds x and y after the append, so its length is 2.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev