Sub topic 3
Building Strings with `StringBuilder`
This chapter assumes you know Java variables, loops, methods, the String class, and the difference between objects and primitives. The examples use Java 15 or later, although StringBuilder itself is available in older Java versions.
Why Use `StringBuilder`?
A String is immutable. This means that its characters cannot change after the object is created. An operation that appears to modify a string actually creates another String object.
For example:
String name = "Ada";
name = name + " Lovelace";The original "Ada" object is unchanged. Java creates a new string containing "Ada Lovelace" and assigns that new object to name.
This behavior is useful because immutable objects are predictable. However, repeated concatenation can create extra work:
String result = "";
for (int i = 0; i < 5; i++) {
result += i;
}
System.out.println(result); // 01234Each += operation creates a new string containing the previous result and the new value. With a small loop, this does not matter. With a large loop, repeatedly copying the accumulated text can be inefficient.
StringBuilder is a mutable character sequence. Mutable means that its contents can change without creating a new builder for every operation.
Creating and Appending
Create a builder with a constructor:
StringBuilder builder = new StringBuilder();Use append to add values to its end. The method accepts strings, numbers, characters, booleans, and other common Java values.
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("User: ");
builder.append("Ada");
builder.append(", score: ");
builder.append(42);
String message = builder.toString();
System.out.println(message);
}
}The output is:
User: Ada, score: 42The builder changes as each append call runs. toString() creates an ordinary immutable String containing the current contents. Use toString() when the finished value must be passed to code that expects a String.
append returns the same StringBuilder, so calls can be chained:
StringBuilder builder = new StringBuilder();
builder.append("Item ")
.append(1)
.append(": ")
.append("Notebook");
System.out.println(builder.toString());The output is:
Item 1: NotebookChaining is a style choice. Separate calls can be easier to debug, while chaining can make a short sequence of additions easier to read.
Building Text in a Loop
A common use for StringBuilder is collecting output during a loop.
public class ListBuilder {
public static void main(String[] args) {
StringBuilder output = new StringBuilder();
for (int i = 1; i <= 3; i++) {
output.append("Item ")
.append(i)
.append('\n');
}
String result = output.toString();
System.out.print(result);
}
}The '\n' value is a single newline character. The output is:
Item 1
Item 2
Item 3The builder stores all three lines in one growing character buffer. The final conversion produces one String.
The same pattern works for generated reports, log messages, CSV rows, and formatted fragments. Keep the data-building step separate from the final output step when that makes the code clearer.
The Working Model
The following diagram shows the typical process:
A StringBuilder is usually a local object used by one method. After construction is complete, return its String result rather than exposing the builder itself:
public static String makeGreeting(String name) {
return new StringBuilder()
.append("Hello, ")
.append(name)
.append("!")
.toString();
}This method uses the builder internally and returns the stable, immutable result.
Exercise
Why is StringBuilder usually more efficient than repeated += inside a large loop?
Show answer
StringBuilder changes one mutable character sequence, while repeated += creates a new String and copies the accumulated text on each iteration.