StringBuilder
A String is immutable: every join with + creates a new object. When text is assembled from hundreds of pieces, that is wasteful. The StringBuilder class holds a mutable string: you can extend and edit it in place, and get a finished String at the end.
append
The object is created with new StringBuilder(). The append() method adds a value at the end, and toString() returns the resulting string:
void main() {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("world");
IO.println(sb.toString());
}Output:
Hello, worldappend() also accepts numbers, characters and boolean values: they are turned into text. You can pass initial text right at creation: new StringBuilder("Java").
Building in a loop
The main use of StringBuilder is building a string in a loop. There is one object, and it simply grows:
void main() {
StringBuilder line = new StringBuilder();
for (int i = 1; i <= 5; i++) {
line.append(i);
if (i < 5) {
line.append(" -> ");
}
}
IO.println(line);
}Output:
1 -> 2 -> 3 -> 4 -> 5IO.println() calls toString() itself, so you can pass the object directly.
Call chains
append() and most other methods return the same StringBuilder object. So calls can be written as a chain of dots:
void main() {
String receipt = new StringBuilder()
.append("Latte: $")
.append(4.5)
.append(", cups: ")
.append(2)
.toString();
IO.println(receipt);
}Output:
Latte: $4.5, cups: 2Changing the contents
insert() inserts a value at an index, deleteCharAt() removes a character, setCharAt() replaces one, and reverse() reverses the string. length() works just like on String:
void main() {
StringBuilder sb = new StringBuilder("Java");
sb.insert(0, "I learn ");
IO.println(sb);
sb.deleteCharAt(sb.length() - 1);
IO.println(sb);
IO.println(new StringBuilder("level").reverse());
IO.println(new StringBuilder("12345").reverse());
}Output:
I learn Java
I learn Jav
level
54321When you need StringBuilder
For joining a few values in a single line of code, + is simpler and no slower — the compiler optimizes such an expression itself. StringBuilder is for when a string is built piece by piece in a loop or in several places of the program. Internally it keeps spare capacity and grows it as needed, so appending to the end is almost always fast.
Common mistake
You cannot compare a StringBuilder with a string using equals(): for it this method only checks whether it is the same object:
void main() {
StringBuilder sb = new StringBuilder("cat");
IO.println(sb.equals("cat"));
IO.println(sb.toString().equals("cat"));
}Output:
false
trueFirst turn the object into a string with toString(), then compare.