Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

StringBuilder.append()

Adds a value to the end of a StringBuilder.

Available since: Java 5

Syntax

public StringBuilder append(Object obj)

Parameters

ParameterTypeDescription
objObject, String, int, char, double…What to add: a string, a number, a char, a boolean or any object (via its toString()).

Return value

StringBuilderThe same StringBuilder, so calls can be chained.

Examples

Chained calls:

void main() {
    var sb = new StringBuilder();
    sb.append("Total: ").append(3).append(" items, ").append(4.5).append('$');
    IO.println(sb);
}

Output:

Total: 3 items, 4.5$

A comma-separated list without a trailing comma:

void main() {
    String[] names = {"Anna", "Oleg", "Maria"};
    var sb = new StringBuilder();
    for (String name : names) {
        if (!sb.isEmpty()) {
            sb.append(", ");
        }
        sb.append(name);
    }
    IO.println(sb);
}

Output:

Anna, Oleg, Maria

Notes

append(char) adds a character while append(int) adds a number: sb.append('a' + 1) adds 98, because 'a' + 1 is an int. isEmpty() on StringBuilder was added in Java 15.

See also

Related recipes

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.