Sub topic 9
Building Strings Efficiently
When you join text many times, a StringBuilder can help. It is a Java class that collects text and lets you add to it as you go. When you are done, it can give you a String.
This matters because a String is immutable: its contents cannot change after it is made. Repeatedly joining strings in a loop can create many temporary strings and copy earlier text again and again. A StringBuilder is mutable, which means its contents can change.
For a small, fixed number of pieces, using + is usually clear and simple. Consider StringBuilder when you add many pieces, especially inside a loop. The speed difference depends on the program, so measure it if performance matters.
Build a list of numbers
This program builds the text 1, 2, 3. It uses a loop, which repeats a set of instructions.
Save it as BuildText.java:
class BuildText {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 3; i++) {
if (i > 1) builder.append(", ");
builder.append(i);
}
String result = builder.toString();
System.out.println(result);
}
}Compile and run it from the folder containing the file:
javac BuildText.java
java BuildTextThe output is:
1, 2, 3Follow the additions
The first line inside main creates an empty StringBuilder and stores it in a variable named builder. A variable is a name that holds a value.
The loop uses i to count from 1 through 3. Each pass adds a number to the builder. The append method adds a value to the end of the builder. A method is an action you can ask an object, such as a builder, to perform.
The if statement adds a comma and a space only when i is greater than 1. This keeps a comma from appearing before the first number.
| Pass | Text in the builder |
|---|---|
| 1 | `1` |
| 2 | `1, 2` |
| 3 | `1, 2, 3` |
The call builder.append(i) adds the number as text. You do not need to create a separate string for each number in this example.
Get the finished string
The toString method creates a String from the builder’s current contents:
String result = builder.toString();The builder and the result are separate. If you add more text to builder afterward, the result string stays the same. To get the builder’s new contents as a string, call toString again.
Practice
Exercise
Change the program so it prints 1 | 2 | 3 instead. Which line should you change?
Show answer
Change builder.append(", "); to builder.append(" | ");. Keep it inside the if statement.
Exercise
In the original program, add builder.append(4); immediately after the result line. What does the program print?
Show answer
It still prints 1, 2, 3. The result string was created before 4 was added to the builder.