Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
StringBuilder for the OCP Java 21 exam: why it exists, how chaining returns the same object, the three constructors and the char-capacity trap, append, insert, delete, deleteCharAt, replace, reverse, setLength, Java 21's repeat, index rules, and equality.
kvi5hnuCode Sprout team member7 min readOn this page
A String never changes, so building text piece by piece with += creates a new object at every step. A loop that appends 26 letters creates 27 strings, and all but the last become garbage straight away. StringBuilder solves this with a mutable sequence of characters: an internal array that grows when needed and that methods change in place. The exam tests it almost always in contrast with String. The key questions are: was the object changed, and how many objects are there?
Mutability and chaining
Most StringBuilder methods change the object and return a reference to that same object (this). That makes chaining possible, but it works differently from String chaining:
var a = new StringBuilder("ant");
var b = a.append("ea"); // a and b refer to the SAME object
b = b.append("t").append("er"); // the reassignment changes nothing: b already points there
System.out.println(a + " " + b); // anteater anteater
System.out.println(a == b); // true

To count StringBuilder objects, count the new StringBuilder(…) calls. Everything else is the same object under different names.
A StringBuilder method called as a statement on its own still has its full effect. This is the opposite of String, where an ignored result means nothing happened.
Creating a StringBuilder
new StringBuilder(); // empty, default capacity 16
new StringBuilder("zoo"); // starts with "zoo", capacity 16 + 3
new StringBuilder(50); // empty, room for 50 chars before it has to grow
new StringBuilder(someCharSequence);
Length is how many characters it holds. Capacity is how many it can hold before it has to allocate a larger array. Capacity is a performance detail and grows automatically. You never have to manage it.
Methods shared with String
These work exactly as on String and do not change the builder:
var sb = new StringBuilder("elephant");
sb.charAt(7); // 't'
sb.length(); // 8
sb.indexOf("ph"); // 3 (also lastIndexOf, and fromIndex overloads)
String sub = sb.substring(0, sb.indexOf("ph")); // "ele" (returns a String)
substring returns a new String and leaves the builder alone. StringBuilder also has codePointAt, codePointBefore, codePointCount, isEmpty() (Java 15), chars() and compareTo (Java 11). It has no strip, toUpperCase, split, startsWith or equalsIgnoreCase. Call toString() first if you need them.
append
StringBuilder append(String s) // plus overloads for boolean, char, int, long, float,
// double, char[], Object, CharSequence, StringBuffer…
Every overload adds a text form of its argument to the end:
String nothing = null;
new StringBuilder().append(1).append('c').append("-").append(true)
.append(2.5).append(nothing).append(new char[] {'!', '?'});
// 1c-true2.5null!?
- A
nullStringorObjectappends the text"null". - A
char[]appends its characters, unlike+, which prints the array'stoString(). append(null)with the literalnulldoesn't compile ("reference to append is ambiguous"), because several overloads could take it.insert(0, null)fails the same way.appendCodePoint(int)appends the Unicode character with that number:appendCodePoint(87)addsW, whileappend(87)adds the digits87, andappend((char) 87)addsW.
insert
StringBuilder insert(int offset, String s) // plus the same overload family as append
Inserts before the character currently at offset. Valid offsets are 0 to length(). Inserting at length() appends. Anything outside that range throws StringIndexOutOfBoundsException. Each insert shifts everything after it, so trace step by step:
var g = new StringBuilder("giraffe");
g.insert(7, "-"); // giraffe- (7 == length: at the end)
g.insert(0, "-"); // -giraffe-
g.insert(4, "-"); // -gir-affe- (index 4 is counted in the CURRENT text)
delete and deleteCharAt
StringBuilder delete(int start, int end) // removes [start, end)
StringBuilder deleteCharAt(int index)
var s = new StringBuilder("abcdef");
s.delete(1, 3); // adef
s.delete(2, 100); // ad (end past the length is clamped to the length)
s.deleteCharAt(5); // StringIndexOutOfBoundsException: index 5, length 2
delete is lenient about the end only. start must still be between 0 and length(), and start > end throws. deleteCharAt has no leniency: the index must point at a real character.
replace
On a StringBuilder, replace works by position, unlike String.replace:
StringBuilder replace(int start, int end, String str)
It works like delete(start, end) followed by insert(start, str), and the replacement doesn't need to have the same length. The end is clamped just as with delete:
new StringBuilder("teapot clean").replace(3, 6, "cup"); // teacup clean
new StringBuilder("teapot clean").replace(3, 100, ""); // tea
new StringBuilder("abcdef").replace(2, 2, "Z"); // abZcdef (pure insert)
reverse, setCharAt, setLength
new StringBuilder("stressed").reverse(); // desserts (surrogate pairs stay intact)
var w = new StringBuilder("hello");
w.setCharAt(0, 'j'); // jello (returns void: can't be chained)
w.setLength(4); // jell: truncates
w.setLength(6); // jell\0\0: pads with the null character '\u0000'
setCharAt and setLength return void, so sb.setLength(2).append("x") doesn't compile.
toString and equality
toString() produces a String with the current contents. That's how a builder's result is handed to code that expects a String. A StringBuilder is not a String: String s = sb; doesn't compile, but String s = sb + ""; does, because concatenation calls toString().
StringBuilder doesn't override equals, so equals compares references, the same as ==:
var x1 = new StringBuilder("same");
var x2 = new StringBuilder("same");
x1.equals(x2); // false: two objects
x1.toString().equals(x2.toString()); // true
x1.compareTo(x2) == 0; // true (Comparable since Java 11)
"same".contentEquals(x1); // true
"a" == new StringBuilder("a") doesn't even compile ("incomparable types"): the compiler knows a String and a StringBuilder can never be the same object. Article 19 covers == and equals for strings in depth.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
repeat(CharSequence, int)andrepeat(int codePoint, int)were added in Java 21 and are fair game on 1Z0-830.StringBufferis the older, synchronized twin ofStringBuilder. It isn't deprecated, but single-threaded code should useStringBuilder.
Exam traps from this article
A complete example
public class Solution {
// Builds a fixed-width receipt line without creating interim Strings
static String receiptLine(String item, int qty, int cents) {
var line = new StringBuilder(32);
line.append(item);
while (line.length() < 12) {
line.append('.');
}
line.append(' ').append(qty).append(" x ")
.append(cents / 100).append('.');
if (cents % 100 < 10) {
line.append('0');
}
return line.append(cents % 100).toString();
}
public static void main(String[] args) {
System.out.println("-- one object, many references --");
var a = new StringBuilder("ant");
var b = a.append("ea");
b = b.append("t").append("er");
System.out.println(a + " " + b + " same object: " + (a == b));
System.out.println("-- constructors and capacity --");
var empty = new StringBuilder();
var seeded = new StringBuilder("zoo");
var sized = new StringBuilder(50);
var trap = new StringBuilder('z'); // char widens to int: capacity 122, no text!
System.out.println(empty.capacity() + " " + seeded.capacity() + " " + sized.capacity()
+ " [" + trap + "] " + trap.capacity());
System.out.println("-- reading like a String --");
var sb = new StringBuilder("elephant");
String sub = sb.substring(sb.indexOf("e"), sb.indexOf("ph"));
System.out.println(sub + " " + sb.length() + " " + sb.charAt(7) + " " + sb);
System.out.println("-- append overloads --");
String nothing = null;
var mixed = new StringBuilder().append(1).append('c').append("-").append(true)
.append(2.5).append(nothing).append(new char[] {'!', '?'});
System.out.println(mixed);
System.out.println(new StringBuilder().appendCodePoint(87).append((char) 87).append(87));
System.out.println("-- insert, delete, replace, reverse --");
var giraffe = new StringBuilder("giraffe");
giraffe.insert(7, "-").insert(0, "-").insert(4, "-");
System.out.println(giraffe);
var letters = new StringBuilder("abcdef");
letters.delete(1, 3);
System.out.println(letters);
letters.delete(2, 100); // end past the length is clamped
System.out.println(letters);
try {
letters.deleteCharAt(5);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("deleteCharAt(5): " + e.getMessage());
}
var teapot = new StringBuilder("teapot clean");
teapot.replace(3, 6, "cup");
System.out.println(teapot + " | " + new StringBuilder("teapot clean").replace(3, 100, ""));
System.out.println(new StringBuilder("stressed").reverse());
System.out.println("-- setLength, setCharAt, repeat (Java 21) --");
var word = new StringBuilder("hello");
word.setCharAt(0, 'j');
word.setLength(4);
System.out.println(word + " " + word.length());
System.out.println(new StringBuilder("ab").repeat("-", 3).repeat('z', 2));
System.out.println("-- equality --");
var x1 = new StringBuilder("same");
var x2 = new StringBuilder("same");
System.out.println(x1.equals(x2) + " " + x1.toString().equals(x2.toString()) + " "
+ (x1.compareTo(x2) == 0) + " " + "same".contentEquals(x1));
System.out.println("-- a practical builder --");
System.out.println(receiptLine("tea", 2, 350));
System.out.println(receiptLine("croissant", 1, 205));
}
}
Output:
-- one object, many references --
anteater anteater same object: true
-- constructors and capacity --
16 19 50 [] 122
-- reading like a String --
ele 8 t elephant
-- append overloads --
1c-true2.5null!?
WW87
-- insert, delete, replace, reverse --
-gir-affe-
adef
ad
deleteCharAt(5): Index 5 out of bounds for length 2
teacup clean | tea
desserts
-- setLength, setCharAt, repeat (Java 21) --
jell 4
ab---zz
-- equality --
false true true true
-- a practical builder --
tea......... 2 x 3.50
croissant... 1 x 2.05
Points to notice:
a == bistrue: one builder, two variables.new StringBuilder('z')prints an empty pair of brackets and has capacity 122.- The inserts into
giraffeuse the current length and indexes after each change. delete(2, 100)clamps the end.deleteCharAt(5)throws.receiptLineshows the typical use: append in a loop, then a singletoString()at the end.x1.equals(x2)isfalse, while comparing theirtoString()values,compareToorcontentEqualsgivestrue.
Common questions
When should I use StringBuilder instead of +?
When you build a string across loop iterations or many statements. For one expression such as a + ":" + b, + is clearer and just as fast.
Is StringBuilder thread-safe?
No. Don't share one between threads without synchronization. StringBuffer is synchronized, but in practice each thread usually builds its own text.
Why doesn't StringBuilder override equals?
It's mutable. An equals based on contents would make it a dangerous HashMap key or HashSet element, because its hash would change whenever it was modified. Compare toString() values, or use compareTo/contentEquals.
Does capacity() matter for the exam?
Only in the char-constructor trap. Capacity is never part of the text and grows on its own.
Summary
StringBuilderis mutable. Its modifying methods change the object and returnthis, so chained calls all act on one object.- Constructors: empty, from a
String/CharSequence, or with anintcapacity, which acharargument silently selects. charAt,indexOf,lengthandsubstringwork like theirStringversions.substringreturns a newString.appendandinserthave overloads for every type.delete(start, end)andreplace(start, end, str)work by position and clamp a large end.deleteCharAt,reverse,setCharAtandsetLengthcomplete the set.toString()produces theString.equalscompares references, so comparetoString()values or usecompareTo.
Practice quiz
Test yourself with the StringBuilder quiz: 10 exam-style questions with explanations.
Previous: Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
Next: Java String Equality: ==, equals, the String Pool and intern (OCP 21)
Related reading
- Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
- Java Strings: Creation, Concatenation and Immutability (OCP 21)
- Java break, continue, Labels, return and Unreachable Code (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.