Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 CharSequence

Examples

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 5

Other 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
10

Notes

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

In the tutorial

  • StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.

Thanks for reading!

Donate to the site — we work hard for you.