0% completed
StringBuilder, StringBuffer, and Concatenation
On This Page
What is the difference between String, StringBuilder, and StringBuffer?
What does the + operator compile to?
Why is concatenation in a loop slow?
Which String methods should you know well?
Predict the Output
Key Takeaways
A store exports its price list as one text of 1,000 lines, and every line has 10 characters. A loop that joins the lines with += copies 5,004,990 characters to build the 10,000 characters of the result. A loop that uses a StringBuilder copies 38,394 characters for the same text.
Both numbers come from a program in this lesson that counts the copies. The four sections that follow compare the three text classes, show what the compiler makes from +, explain the numbers above, and cover the String methods that programs use most.
What is the difference between String, StringBuilder, and StringBuffer?
Level: Junior
A String never changes after it is created, while a StringBuilder and a StringBuffer hold text that can be changed in place. The two builder classes offer the same main methods. The difference between them is that the methods of StringBuffer are synchronized where necessary, which means that only one thread at a time can run such a method on the same object.
A method of String that seems to modify the text returns its result as a separate value. The lesson Strings, the String Pool, and Immutability explains why the class works this way. A builder keeps its characters in an internal array, which is called the buffer. The method append() writes the new characters at the end of that array and returns the same builder, so calls can be chained.
| Class | Can change | Synchronized | Typical use |
|---|---|---|---|
String | No | Not needed | Text that is stored, passed, or compared |
StringBuilder | Yes | No | Text built by one thread |
StringBuffer | Yes | Yes | Old code that shares one buffer |
text = apple joined = apple 120 sb = apple 120 same builder: true sb = red apple 125 equals: false compareTo: 0 contentEquals: true
Compare the first three lines. The call to concat() left text unchanged and returned a new string, while append() changed the builder itself. The last three lines compare two builders that hold the same characters. The builder classes do not override equals(), so it compares the two objects and returns false.
Common mistake: Choosing StringBuffer for all code because it sounds safer. A builder in a local variable is normally used by one thread, so the locks protect nothing. The Javadoc recommends StringBuilder for that case.
Follow-up questions
1. Does a shared StringBuffer make a log correct when two threads write to it?
Each call is safe, but a group of calls is not. One thread may call append("Ana") and then append(" paid"). A second thread can append its own text between those two calls, so the result can mix two messages. The thread needs one lock around the whole group, or one append() call with a complete message.
2. How do you compare the text of two builders?
<details><summary>Show answer</summary>Use compareTo(), which returns 0 for equal text, or convert both builders to strings and call equals(). StringBuilder has implemented Comparable since Java 11. To compare a String with a builder, call contentEquals() on the string. The call "apple".equals(sb) is always false, because the argument is not a String.
What does the + operator compile to?
Level: Mid-level
Since Java 9, the compiler normally turns a string concatenation into one invokedynamic instruction that calls a method prepared by the class StringConcatFactory. Constant parts are joined during compilation. Before Java 9, the compiler wrote a chain of StringBuilder calls instead.
The instruction invokedynamic calls a method that is chosen when the program runs. When the JVM reaches the instruction for the first time, it asks StringConcatFactory for a method that fits the types of the values. The JVM connects the instruction to that method, and later executions call it directly. An expression that joins 200 values needs more than one instruction. The class below contains two concatenations.
public class Labels { static String label(String name, int cents) { return name + ": " + cents + " cents"; } static String fixed() { return "apple" + ": " + 120; } }
The command javap -c, which the lesson From Source Code to a Running Program introduces, prints the bytecode. This is the part for the two methods, compiled for Java 17:
static java.lang.String label(java.lang.String, int); Code: 0: aload_0 1: iload_1 2: invokedynamic #7, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;I)Ljava/lang/String; 7: areturn static java.lang.String fixed(); Code: 0: ldc #11 // String apple: 120 2: areturn
The method label() places the name and the price on the stack and runs one invokedynamic instruction. The fixed texts are not passed as values, because the class file stores them in a pattern for the factory. The method fixed() performs no concatenation when it runs. All three of its parts are constants, so the compiler joined them into "apple: 120".
Compiled with --release 8, the same label() creates a builder. This listing is shortened:
0: new #7 // class java/lang/StringBuilder 8: invokevirtual #10 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 17: invokevirtual #16 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 25: invokevirtual #21 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
Common mistake: Replacing every + with a StringBuilder. One expression already becomes one operation, so the replacement makes the code longer without saving copies.
Follow-up questions
1. What does + do with a null value?
It adds the four characters null and throws no exception. When name is null, the expression "name: " + name gives "name: null". A builder does the same when append() receives a String that is null. The method concat() is different, because it calls a method on its argument and throws a NullPointerException.
2. Why did Java 9 stop writing the builder calls into the class file?
<details><summary>Show answer</summary>The new form lets the Java runtime improve concatenation without a new compilation. The class file states only which values and fixed texts must be joined. The library decides how to join them when the program runs. An application compiled for Java 9 therefore uses the method of the runtime it runs on, while a class with builder calls keeps those calls.
</details>Why is concatenation in a loop slow?
Level: Mid-level
Each += creates a new string and copies all the earlier characters into it, so the total number of copies grows with the square of the number of lines. A StringBuilder adds each line at the end of its buffer and copies the earlier characters only when the buffer is full.
Suppose the text of the price list starts as the first line. The first += copies 20 characters, the second copies 30, and the last one copies 10,000. The sum is 10 x (2 + 3 + ... + 1,000), which is 10 x 500,499, or 5,004,990. This growth is called quadratic, written O(n²): ten times as many lines need about one hundred times as many copies.
10 lines: += copies 540, builder copies 320 100 lines: += copies 50490, builder copies 3122 1000 lines: += copies 5004990, builder copies 38394
Read the output by rows. From 100 to 1,000 lines, the += loop needs about 99 times as many copies, and the builder needs about 12 times as many. At 10 lines, both numbers are small and the choice hardly matters.
Look at the two rows, which join only four lines. The += row copies 20 + 30 + 40 characters, which is 90, and only the last of its three new strings is the result. The builder row starts with new StringBuilder(40) and writes 40 characters into one array. The picture stops before toString(), which would copy these 40 characters once more.
The builder has a cost of its own, because its buffer must grow. The next program prints the capacity, which is the number of characters that fit before the array must be replaced.
length 0, capacity 16 length 17, capacity 34 length 35, capacity 70 length 71, capacity 142 from a text: 21
The default capacity is 16. When a character does not fit, the builder normally creates an array of twice the old capacity plus 2 and copies the old array. A builder created from a text starts with the length of the text plus 16. For the 1,000 lines, all growth steps together copy 18,394 characters. Adding the lines copies 10,000, and toString() copies 10,000 once more, which gives 38,394.
Common mistake: Saying that the compiler turns a += loop into one builder. The compiler treats each += as its own expression. Neither of the two compiled forms above places a single builder around the loop.
Follow-up questions
1. How many copies does new StringBuilder(10_000) save for the 1,000 lines?
It saves the 18,394 copies that the growth steps make. The buffer starts with room for the whole result, so it never grows. The loop then copies 10,000 characters and toString() copies 10,000, which is 20,000 in total. The argument is a capacity, so the builder is still empty when it is created.
2. How do you reuse one builder for several texts?
<details><summary>Show answer</summary>Call setLength(0) after toString(), which empties the builder and keeps its buffer. The string returned earlier is not affected, because toString() copied the characters. The method can also remove a last separator: sb.setLength(sb.length() - 1) deletes the final character.
Which String methods should you know well?
Level: Junior
The most useful ones remove white space, test for empty text, split and join, search, and compare. They return a result and leave the original string unchanged. Several of them have details that cause errors.
| Method | Detail |
|---|---|
strip(), trim() | Both work at the two ends. strip() uses Character.isWhitespace(), and trim() removes character codes up to 32 |
isEmpty(), isBlank() | Length 0, or nothing except white space |
repeat(n), join() | Repeat a text n times, or join texts with a separator |
split(regex) | The argument is a regular expression, which is a search pattern |
substring(from, to) | to is excluded, and the characters are copied |
indexOf(text, from) | Returns -1 when the text is absent |
equalsIgnoreCase() | Compares without regard to case |
chars() | A stream of int values |
The methods strip(), isBlank(), and repeat() were added in Java 11.
trim length = 6 strip length = 5 isEmpty = false, isBlank = true kiwi kiwi kiwi apple, banana, cherry [apple, 50] 3 true ana 3
The first two lines use a name that starts with the wide space U+3000, whose code is 12,288. The method trim() removed only the ordinary space at the end, so 6 characters remain. strip() removed both. The last line shows a search that starts at index 2 and finds the second "an" at index 3.
Common mistake: Passing a plain separator such as "|" or "." to split(). Both have a special meaning in a regular expression. Write "\\|" and "\\.", or call Pattern.quote().
Follow-up questions
1. Why should code that is not shown to users call toLowerCase(Locale.ROOT)?
Without an argument, the method uses the default locale of the JVM, and the rules differ between languages. A locale is a language and region setting. In Turkish, the lowercase form of I is a letter without a dot, so "KIWI".toLowerCase() does not equal "kiwi" when the default locale is Turkish. Locale.ROOT gives the same result on every machine.
2. Does substring() share the characters of the original string?
No, current versions copy the selected characters into a new array. A short substring of a 10 MB text therefore does not keep the large array in memory. A call that selects the whole string copies nothing and returns the same object.
</details>Predict the Output
The program splits six texts and prints the number of parts. Write down the six numbers, and then press Run.
The program prints 2, 4, 2, 0, 2, and 1. The one-argument split() drops empty parts at the end, so "apple,banana,," gives two parts. A negative limit keeps them and gives four. An empty part at the start is kept, so ",apple" gives two. The pattern "." matches each character of this text, so every part is empty, all of them are dropped, and the array has length 0. The pattern "\\." matches a real period and gives two parts. An empty text contains no separator, so the result holds the original empty string.
Key Takeaways
- A
Stringnever changes.StringBuilderchanges in place without locks, andStringBufferadds a lock to each call. - Since Java 9, a
+expression becomes oneinvokedynamicinstruction, and constant parts are joined by the compiler. - A
+=loop copies all earlier characters at every step, which is quadratic. - A builder buffer starts at 16 characters and normally grows to twice its capacity plus 2. A known size can be passed to the constructor.
strip()removes Unicode white space such as U+3000, whiletrim()removes only character codes up to 32.split()takes a regular expression and drops empty parts at the end.
This lesson called static methods such as String.join() and used constants such as a static final text. The lesson static, final, and Initialization Order explains both words and the order in which Java gives fields their values.
Reading Progress
0%
On This Page
What is the difference between String, StringBuilder, and StringBuffer?
What does the + operator compile to?
Why is concatenation in a loop slow?
Which String methods should you know well?
Predict the Output
Key Takeaways