Sub topic 9
Building Strings Efficiently
A Java String holds text that cannot be changed after it is created. This property is called immutability. When you combine or change strings, the result is a new string.
That is often fine. But when you build a long piece of text by adding many small pieces, creating a new string for each addition can mean extra work. A StringBuilder helps with this task.
A StringBuilder is an object that holds text you can change. You can add pieces to it, then ask it for a finished String.
When to use a StringBuilder
Use StringBuilder when you add pieces of text many times, especially inside a loop. A loop repeats a set of instructions. The number of pieces may depend on the data your program receives.
For a small, fixed combination, the + operator is usually clear and convenient:
String greeting = "Hello, " + name + "!";There is no need to replace every use of + with a StringBuilder. Choose the approach that keeps the code clear. A builder is most useful when additions repeat.
Build a list of numbers
This example builds the text 1, 2, 3. It adds a comma and a space before each number except the first one.
Save the code 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:
javac BuildText.java
java BuildTextThe output is:
1, 2, 3Here is what happens:
new StringBuilder()creates a builder with no text.- The loop runs with
iset to1,2, and then3. appendis a method that adds a value to the end of the builder. A method is an action you can ask an object to perform.- When
iis greater than1, the program first adds", ". builder.toString()creates aStringcontaining the builder's current text.
The condition i > 1 matters. Without it, the text would start with an unwanted comma and space. It also avoids adding a comma after the last number.
Watch the builder grow
| Step | What is added | Text in the builder |
|---|---|---|
| Start | Nothing | Empty |
| First loop pass | `1` | `1` |
| Second loop pass | `, `, then `2` | `1, 2` |
| Third loop pass | `, `, then `3` | `1, 2, 3` |
A loop pass is one run through the instructions inside a loop.
Add different kinds of values
The append method can add strings, numbers, and other common kinds of values. It turns each value into text as it adds it.
This complete program builds a short message:
class AppendValues {
public static void main(String[] args) {
StringBuilder message = new StringBuilder();
message.append("Score: ");
message.append(42);
message.append(" points");
System.out.println(message.toString());
}
}Save it as AppendValues.java, then compile and run it as you did with BuildText. It prints:
Score: 42 pointsYou can also put these calls together:
class ChainedAppend {
public static void main(String[] args) {
StringBuilder message = new StringBuilder();
message.append("Score: ").append(42).append(" points");
System.out.println(message.toString());
}
}This is called chaining: each append returns the same builder, so the next append can act on it. Chaining is useful for a few short additions. If a chain gets hard to read, use separate lines instead.
A builder can change; a String cannot
A StringBuilder is mutable, which means its contents can change. Calling append changes the builder you already have. You do not need to create a new builder for each addition.
The String returned by toString() is different. It holds the text as it was when you called the method. Later changes to the builder do not change that string.
class BuilderSnapshot {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("Good");
String first = builder.toString();
builder.append(" morning");
String second = builder.toString();
System.out.println(first);
System.out.println(second);
}
}Save this as BuilderSnapshot.java. It prints:
Good
Good morningThe builder starts with "Good" because that text is supplied when the builder is created. The variable first keeps the string "Good". Adding more text to the builder does not change first.
Change or clear builder text
Besides adding to the end, a builder can insert or remove text. These methods use an index, which is a position in the text. Positions start at 0.
| Method | What it does |
|---|---|
| `append(value)` | Adds a value at the end |
| `insert(index, value)` | Adds a value at a position |
| `delete(start, end)` | Removes text from `start` up to, but not including, `end` |
| `setLength(0)` | Clears all text from the builder |
| `length()` | Returns the current number of positions in the builder |
For example:
class EditText {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("cat");
builder.insert(0, "The ");
System.out.println(builder.toString());
builder.delete(0, 4);
System.out.println(builder.toString());
builder.setLength(0);
builder.append("dog");
System.out.println(builder.toString());
}
}Save this as EditText.java. It prints:
The cat
cat
dogThe first call inserts "The " at position 0, before the existing text. The delete(0, 4) call removes positions 0 through 3: the three letters and the space. Position 4 is not removed.
Finally, setLength(0) clears the builder. The same builder can then be used to build new text.
Be careful with positions. For example, trying to insert beyond the end of the builder causes an error. Check length() when you need to know where the text ends.
Sharing a builder
A variable that holds a StringBuilder refers to that builder. If you assign it to another variable, both variables refer to the same builder. They do not hold separate copies.
class SharedBuilder {
public static void main(String[] args) {
StringBuilder first = new StringBuilder("tea");
StringBuilder second = first;
second.append(" cup");
System.out.println(first.toString());
System.out.println(second.toString());
}
}Save this as SharedBuilder.java. Both lines print tea cup because both variables refer to the same builder.
To start a separate builder with the same text, create a new one:
class SeparateBuilders {
public static void main(String[] args) {
StringBuilder first = new StringBuilder("tea");
StringBuilder second = new StringBuilder(first.toString());
second.append(" cup");
System.out.println(first.toString());
System.out.println(second.toString());
}
}This time, the first line is tea and the second is tea cup.
How a builder helps
A builder keeps space for text as it grows. Its capacity is the amount of text it can hold before it needs more space. If you append more text than fits, the builder obtains more space automatically.
You can give a starting capacity when you create a builder:
class BuilderCapacity {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder(100);
builder.append("Hello");
System.out.println(builder.length());
}
}The starting capacity is 100, but the program prints 5. Capacity is space available; length is the amount of text currently held. The builder starts empty, even when you give it a capacity.
You usually do not need to choose a capacity. If you have a useful estimate for a large result, giving one may reduce the need to obtain more space. The builder can still grow beyond it.
A builder can reduce work when many pieces are added because it does not need to make a finished String after every addition. The actual speed difference depends on the program. For a few pieces, prefer clear code over trying to save a tiny amount of work.
Check your understanding
Exercise
A builder starts empty. You append "red", then ", ", then "blue". What does toString() return?
Show answer
It returns the String "red, blue".
Exercise
You call toString() on a builder and store the result. Then you append more text to the builder. Does the stored String change?
Show answer
No. The stored String keeps the text that the builder held when toString() was called.
Exercise
Why might a StringBuilder be useful when a loop adds hundreds of pieces to one result?
Show answer
It lets the program add pieces to one mutable builder and create the finished String at the end, rather than making a new finished String after every addition.