Syntax
new StringBuilder().append(value).append(other).toString()Examples
Building Text with StringBuilder
Save as Main.java and run with a Java 17+ JDK: java Main.java.
import java.lang.StringBuilder;
public class Main {
public static void main(String[] args) throws Exception {
StringBuilder text = new StringBuilder();
for (int i = 1; i <= 3; i++) {
if (i > 1) text.append(", ");
text.append("item-").append(i);
}
System.out.println(text.toString());
}
}- Expected output: item-1, item-2, item-3
- The loop adds separators only between items and reuses one buffer throughout the accumulation.
Best practices
- Prefer ordinary concatenation for short fixed expressions.
- Do not share a StringBuilder across threads without synchronization.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification