Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java StringBuilder append: Syntax and Performance

How Java's StringBuilder.append builds strings efficiently: syntax, chaining, capacity growth, and when it beats concatenation.

~3 min readJava
#StringBuilder#String Concatenation#Java Performance#Mutable Strings
Diagram showing a StringBuilder buffer being extended by append operations, with the final toString result.

Java's String class is immutable, so at runtime a non-constant concatenation creates a new String object. When you build a string incrementally inside a loop, that behavior produces a new intermediate object on each iteration. StringBuilder's append method solves this problem by mutating a single internal buffer in place.

Why String Concatenation Creates Unnecessary Objects

Consider this common pattern:

java
String result = ""; for (int i = 0; i < 1000; i++) { result += i; }

Each += creates a new String, copies the previous content, and appends the new digits. The previous String becomes garbage. Over many iterations, this produces hundreds or thousands of short-lived objects that the garbage collector must reclaim. The cost is not just allocation but also the repeated copying of the growing character array.

The compiler may optimize a single concatenation expression such as "id=" + id + ", name=" + name so that it does not create a separate intermediate String for every +. Inside a loop, however, that optimization still does not give you one reusable buffer across iterations. An explicit StringBuilder created once outside the loop gives you predictable behavior and avoids the repeated allocation.

StringBuilder append Basic Syntax

The append method adds a value to the end of the current buffer and returns the same StringBuilder instance:

java
StringBuilder sb = new StringBuilder(); sb.append("Order #"); sb.append(1042); sb.append(" total: "); sb.append(29.95); String message = sb.toString();

Each call mutates the existing buffer rather than creating a new String. The toString() call at the end produces the final String. If you need to keep building after calling toString(), the builder still holds its content and you can append more; the returned String is a snapshot of the current state.

Chaining append Calls

Because append returns the StringBuilder itself, you can chain calls in a single expression:

java
StringBuilder sb = new StringBuilder(); sb.append("User: ").append(user.getName()).append(" (id ").append(user.getId()).append(")");

This reads naturally when the sequence of parts is known in advance. For conditional appends, where a part should only be added under some condition, separate statements are usually clearer:

java
if (user.isActive()) { sb.append("active"); } else { sb.append("inactive"); }

Overloaded append Variants

StringBuilder provides overloads for String, char[], CharSequence, StringBuffer, and Object, plus overloads for boolean, char, int, long, float, and double. A byte or short argument is widened to the int overload. Common examples:

Argument typeExample call
Stringsb.append("text")
charsb.append('x')
intsb.append(42)
longsb.append(42L)
floatsb.append(3.14f)
doublesb.append(3.14)
booleansb.append(true)
char[]sb.append(new char[]{'a','b'})
Objectsb.append(someObject)

The Object overload calls String.valueOf(Object), which returns "null" for a null reference; the String, CharSequence, and StringBuffer overloads append the text "null" when passed null. Passing a null char[] to append(char[]), by contrast, throws NullPointerException. If you need to distinguish a null value from the literal text "null", check for null before appending.

Capacity and Buffer Growth

A StringBuilder has an internal character array with a current capacity. When appending would exceed that capacity, the builder allocates a new, larger array and copies the existing characters into it. That reallocation is the main cost of growing a builder gradually.

You can set an initial capacity when you know the approximate final size:

java
StringBuilder sb = new StringBuilder(1024);

This avoids several reallocations when building a large string. If the final size is unknown but the builder will grow substantially, a reasonable initial capacity still reduces the number of copies. The exact growth factor is implementation-defined and you should not rely on it; the contract only guarantees that the builder expands as needed.

Thread Safety and Concurrency

StringBuilder is not thread-safe. If multiple threads append to the same instance without external synchronization, the internal state can be corrupted. The synchronized alternative, StringBuffer, offers the same append API but with method-level locking. For a builder that is created and used within a single thread, StringBuilder is the appropriate choice. If the builder must be shared across threads, either synchronize access yourself or use StringBuffer, and measure whether the locking cost matters in your workload.

When String.join or String.format Is a Better Choice

StringBuilder is the right tool for incremental construction where parts are added over time, often conditionally. For joining a collection of strings with a delimiter, String.join is more readable:

java
String csv = String.join(", ", names);

For producing a formatted value with placeholders, String.format is clearer:

java
String line = String.format("%s: %d", name, count);

StringBuilder remains the better fit when the number of parts is not known in advance, when parts are added across multiple method calls, or when you want to reuse the buffer for building several strings sequentially.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.