Sub topic 3
Building Strings with StringBuilder
This chapter assumes you can write basic Java (variables, loops, methods) and know how String and the + operator work. You should also know the difference between objects and primitives. Any recent JDK runs the examples.
By the end you will be able to:
- Create a
StringBuilderwith each constructor. - Choose the right
appendoverload. - Convert the result with
toString. - Avoid the common mistakes that make builder code slow or wrong.
Why a Builder Exists
A String is immutable: once created, its characters never change. An operation like s += i therefore builds a brand-new String from the old text plus the new piece, then points s at it. Inside a loop, the text accumulated so far is copied again on every pass.
public class ConcatLoop {
public static void main(String[] args) {
String s = "";
for (int i = 0; i < 5; i++) {
s += i;
}
System.out.println(s); // 01234
}
}With 5 iterations the cost is invisible. With 100,000 iterations, the total number of characters copied grows roughly with the square of the iteration count. This is the cost the previous chapter measured.
StringBuilder (in java.lang, so no import is needed) removes that cost. It is a mutable sequence of characters. It keeps one internal buffer and writes new text into it. Copying happens only when the buffer runs out of room, and then it grows by a large step instead of one character at a time.
The same loop with a builder:
public class BuilderLoop {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i);
}
System.out.println(sb); // 01234
}
}The lifecycle has three steps: create the builder, append to it as many times as needed, then convert it to a String once.
Creating a StringBuilder
There are four constructors.
| Constructor | Result |
|---|---|
| `new StringBuilder()` | Empty builder with a default initial capacity of 16 characters |
| `new StringBuilder(int capacity)` | Empty builder with room for `capacity` characters |
| `new StringBuilder(String str)` | Builder holding a copy of `str`, with extra room |
| `new StringBuilder(CharSequence seq)` | Builder holding a copy of the characters in `seq` |
The int constructor sets only the size of the internal buffer, not the content. new StringBuilder(64) is an empty builder whose length() is 0. A later chapter covers capacity and when presizing helps.
The int constructor has a trap with char. A char widens to int, so new StringBuilder('A') does not start the builder with the text A. It creates an empty builder with a capacity of 65 (the numeric value of 'A'). If you want the text, pass a String: new StringBuilder("A").
The String and CharSequence constructors throw a NullPointerException if you pass null. They do not create a builder containing the text "null".
Appending Values
append adds to the end of the builder. It is heavily overloaded, so you can pass almost any value without converting it first:
append(String),append(CharSequence),append(StringBuffer)append(char),append(char[])append(int),append(long),append(float),append(double)append(boolean)append(Object), which usesString.valueOf(obj)
Each overload converts its argument to text the same way String.valueOf does, then adds those characters to the buffer.
Every append returns the same builder (this). That is what makes chaining work:
public class AppendChain {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append("Item ").append(i).append('\n');
}
String result = sb.toString();
System.out.print(result);
}
}This prints:
Item 1
Item 2
Item 3sb.append("Item ").append(i).append('\n') is three separate calls on one object. No new builder is created, and sb is modified directly. Because the method mutates the builder, you do not have to assign the return value back. The line sb.append("x"); on its own is enough. This differs from String methods such as concat or toUpperCase, where ignoring the return value does nothing.
Overload Behavior to Know
A few overloads behave in ways that surprise people.
public class AppendOverloads {
public static void main(String[] args) {
String missing = null;
System.out.println(new StringBuilder().append('a')); // a
System.out.println(new StringBuilder().append((int) 'a')); // 97
System.out.println(new StringBuilder().append('a' + 1)); // 98
System.out.println(new StringBuilder().append((char) ('a' + 1))); // b
System.out.println(new StringBuilder().append(missing)); // null
System.out.println(new StringBuilder().append(1.0)); // 1.0
System.out.println(new StringBuilder().append(true)); // true
System.out.println(new StringBuilder().append(new char[] {'x', 'y'})); // xy
System.out.println(new StringBuilder().append("hello", 1, 3)); // el
}
}The points to take from this output:
charandintare different overloads.append('a')adds the character.append('a' + 1)computes anint(98) first, so it appends the digits98. Cast tocharif you want the next letter.- A
nullString appends the four lettersnull. No exception is thrown. This can hide a missing value in your output, so check fornullyourself when it matters. append(CharSequence, int start, int end)appends a range. Theendindex is exclusive, so"hello"with1, 3givesel.append(char[])appends the characters in the array. It does not print the array's identity the way string concatenation of an array does.
One related point is that + is not always a problem. Since Java 9, a single expression such as "Hello, " + name + "!" compiles to code that builds the result efficiently in one step. The slow case is accumulation across iterations, where each pass creates a new String from the previous one. If you build a string in a loop, use a builder. For a one-line expression, + is fine.
Getting the Result Out
A StringBuilder is not a String. You cannot pass it to a method that takes a String parameter. Call toString() to get one:
String text = sb.toString();toString() makes a new immutable String containing a copy of the current characters. Two consequences follow:
- The builder and the returned
Stringare independent. Changing the builder afterward does not change theStringyou already took. - Each
toString()call copies the whole content. Call it once, after you finish building, and not inside the loop.
public class Snapshot {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("abc");
String first = sb.toString();
sb.append("def");
System.out.println(first); // abc
System.out.println(sb); // abcdef
}
}Many APIs accept a CharSequence instead of a String, and StringBuilder implements CharSequence. You can often pass the builder directly. Examples are String.join, String.contentEquals, and Appendable consumers. System.out.println(sb) and string concatenation ("x" + sb) also work, because both call toString() for you.
Reading What You Built
A builder supports a few read operations without converting:
public class ReadBuilder {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
System.out.println(sb.length()); // 4
System.out.println(sb.charAt(0)); // J
System.out.println(sb.indexOf("va")); // 2
System.out.println(sb.substring(1, 3)); // av
}
}length()is the number of characters stored. It is not the capacity.charAt(int)throwsStringIndexOutOfBoundsExceptionfor an invalid index.indexOfandlastIndexOfsearch the builder's contents and return-1when nothing is found.substring(start, end)returns a newString. The builder itself is unchanged.
The next chapter covers the methods that edit the content in place.
Comparing Builders
StringBuilder does not override equals, so it inherits identity comparison from Object:
public class BuilderEquality {
public static void main(String[] args) {
StringBuilder a = new StringBuilder("abc");
StringBuilder b = new StringBuilder("abc");
System.out.println(a.equals(b)); // false
System.out.println(a.toString().equals(b.toString())); // true
System.out.println("abc".contentEquals(a)); // true
System.out.println(a.compareTo(b)); // 0
}
}a.equals(b) is false even though the text matches, because a and b are different objects. To compare contents, use String.contentEquals(CharSequence), compare the toString() results, or use compareTo (available since Java 11), which returns 0 for equal content.
This also means a StringBuilder is a poor key for a HashMap or element for a HashSet. It has no content-based equals or hashCode, and it is mutable. Convert to a String first.
A Practical Pattern: Separators
A common job is joining values with a separator, with no separator after the last one. A builder handles it with a check on the current length:
import java.util.List;
public class JoinWithBuilder {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Linus");
StringBuilder sb = new StringBuilder();
for (String name : names) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(name);
}
System.out.println(sb); // Ada, Grace, Linus
}
}The check sb.length() > 0 is true from the second pass onward, so the separator goes only between items. If your items can be empty strings, this check can misfire, so use a boolean flag or an index instead. When the job is only joining a collection, String.join(", ", names) is shorter and equally efficient. The final chapter compares these options.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `new StringBuilder('A')` | Empty builder with capacity 65, not the text `A` | `new StringBuilder("A")` |
| `sb.append('a' + 1)` | Appends `98` | Cast: `(char) ('a' + 1)` |
| `sb.append(a + b + c)` | Builds a temporary String first | Chain separate `append` calls |
| `sb.toString()` inside a loop | Copies the whole buffer on every pass | Call it once after the loop |
| `sb1.equals(sb2)` | Compares identity, so usually `false` | `sb1.compareTo(sb2) == 0` or compare Strings |
| Appending a `null` String | Silently adds `null` | Check for `null` before appending |
Summary
A StringBuilder holds a mutable buffer of characters. You create it with one of four constructors, add to it with the many append overloads (each returns the same builder, so calls chain), and convert it once with toString(). Watch the char versus int overloads, the null behavior, and the lack of content-based equals.
Exercise
What does the following program print, and why? StringBuilder sb = new StringBuilder('B'); sb.append('B').append('B' + 1).append((char) ('B' + 1)); System.out.println(sb.length() + " " + sb);
Show answer
It prints "5 BBC". The constructor receives a char, which widens to int, so it creates an empty builder with capacity 66 and no content. append('B') adds the character B. append('B' + 1) computes the int 67 and appends the digits "67" (two characters). append((char) ('B' + 1)) appends the character C. The content is "B67C", so the length is 4 and the output is "4 B67C". Check: the correct answer is 4 B67C, not 5 BBC.
Exercise
A method builds a report in a loop. Each pass calls sb.append(row) and then logs sb.toString(). The report has 50,000 rows and the method is slow. What is the cause, and how do you fix it?
Show answer
Each toString() call copies the entire accumulated content into a new String, so the total copying grows roughly with the square of the row count, the same cost as concatenating Strings in a loop. Remove toString() from the loop. Log only the new row, or call toString() once after the loop finishes.