StringBuilder.append()
Adds a value to the end of a StringBuilder.
Available since: Java 5
Syntax
public StringBuilder append(Object obj)Parameters
| Parameter | Type | Description |
|---|---|---|
| obj | Object, 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, MariaNotes
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
- StringBuilder — A mutable string: useful when text is built piece by piece, especially in a loop.
- StringBuilder.insert() — Inserts a value at the given position of a StringBuilder.
- StringBuilder.toString() — Returns the contents of a StringBuilder as a regular String.
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.