StringBuilder
A mutable string: useful when text is built piece by piece, especially in a loop.
Available since: Java 5
Syntax
public final class StringBuilder implements CharSequenceExamples
Building a string in a loop:
void main() {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(' ');
}
IO.println(sb.toString().strip());
}Output:
1 2 3 4 5Other useful methods — length(), setCharAt(), replace():
void main() {
var sb = new StringBuilder("hello world");
sb.setCharAt(0, 'H');
sb.replace(6, 11, "Java");
IO.println(sb);
IO.println(sb.length());
}Output:
Hello Java
10Notes
String is immutable: every s = s + x creates a new string, which is slow in a long loop. StringBuilder changes one buffer. For a single string outside a loop, plain + concatenation is fine — the compiler optimizes it.
StringBuilder is not thread-safe. The older StringBuffer class has the same methods and is synchronized, but it is slower and rarely needed. equals() on StringBuilder compares references, not contents — compare sb.toString() or use compareTo().
See also
- StringBuilder.append() — Adds a value to the end of a StringBuilder.
- StringBuilder.insert() — Inserts a value at the given position of a StringBuilder.
- StringBuilder.reverse() — Reverses the contents of a StringBuilder.
- StringBuilder.toString() — Returns the contents of a StringBuilder as a regular String.
- StringBuilder.deleteCharAt() — Removes one character at an index. For a range there is delete(start, end).
In the tutorial
- StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.