12.2 StringBuilder Mutability, Capacity & Chaining
Key Takeaways
StringBuilder is a mutable, final CharSequence in java.lang whose mutating methods modify the internal buffer in place and return this for chaining
new StringBuilder() starts with length 0 and capacity 16; new StringBuilder(5) starts with length 0 and capacity 5; new StringBuilder("abc") starts with length 3 and capacity 19 (16 + 3)
delete(start, end) safely clamps end beyond length() without throwing, whereas deleteCharAt(index) throws StringIndexOutOfBoundsException whenever index < 0 or index >= length()
StringBuilder.substring(...) returns a String rather than a StringBuilder and does not mutate the builder, so you cannot chain .append(...) directly onto .substring(...)
StringBuilder does not override Object.equals(Object), so sb1.equals(sb2) compares object references (==) rather than character contents
Mutability vs. Immutability
Run-time String concatenation returns a new string value. To accumulate text across iterations, a java.lang.StringBuilder lets you append to one mutable sequence, which grows its capacity as needed.
Both String and StringBuilder are final classes in java.lang and both implement java.lang.CharSequence. However, their behavior differs sharply:
String: Immutable. Transformation methods leave the receiver unchanged and can return the receiver when their API allows it.StringBuilder: Mutable; methods likeappend,insert,delete,replace, andreversemodify the receiver itself and returnthis.StringBuffer(historical sibling): Provides a similar mutable sequence API with synchronization.StringBuilderis designed for use when synchronization is unnecessary.
Because mutating methods return this (a reference to the same StringBuilder object), two variables sharing a StringBuilder see every mutation made through either variable:
StringBuilder a = new StringBuilder("abc");
StringBuilder b = a.append("de"); // Modifies a in place and returns a
b = b.append("f").reverse();
System.out.println(a); // Prints: fedcba
System.out.println(a == b); // Prints: true
Constructors: length() vs. capacity()
Keep track of the distinction between length (how many UTF-16 code units are currently stored) and capacity (how many UTF-16 code units fit before the buffer needs to grow):
| Constructor Call | Initial Content | Initial length() | Initial capacity() | Common Trap |
|---|---|---|---|---|
new StringBuilder() | "" | 0 | 16 | Default capacity is 16, not 0 |
new StringBuilder(int capacity) | "" | 0 | capacity | new StringBuilder(5) does not hold "5"; length() is 0 |
new StringBuilder(String str) | str | str.length() | 16 + str.length() | null throws NullPointerException |
new StringBuilder(CharSequence cs) | cs | cs.length() | 16 + cs.length() | Works with another StringBuilder |
StringBuilder empty = new StringBuilder();
StringBuilder sized = new StringBuilder(5);
StringBuilder withText = new StringBuilder("Java");
System.out.println(empty.length() + "," + empty.capacity()); // 0,16
System.out.println(sized.length() + "," + sized.capacity()); // 0,5
System.out.println(withText.length() + "," + withText.capacity()); // 4,20
Important
Passing a negative integer to new StringBuilder(-1) throws NegativeArraySizeException at runtime. Calling new StringBuilder(5) compiles cleanly and creates an empty builder with capacity 5 and length() == 0.
Core Mutating and Non-Mutating Methods
Watch return types carefully: mutators return StringBuilder (this), whereas inspection methods return String, char, or int.
| Method | Return Type | Mutates this? | Edge Cases & Exceptions |
|---|---|---|---|
append(X) | StringBuilder | Yes | Overloaded for primitives, String, char[], CharSequence, Object; null Object appends "null" |
insert(int offset, X) | StringBuilder | Yes | Valid 0 <= offset <= length() (offset == length() appends at end); the exact documented exception depends on the overload |
delete(int start, int end) | StringBuilder | Yes | Deletes [start, end); if end > length(), end is clamped to length(); throws if start < 0, start > length(), or start > end |
deleteCharAt(int index) | StringBuilder | Yes | Deletes single char; never clamps—throws StringIndexOutOfBoundsException if index < 0 or index >= length() |
replace(int start, int end, String str) | StringBuilder | Yes | Replaces [start, end) with str (lengths need not match); clamps end > length() |
reverse() | StringBuilder | Yes | Reverses the sequence in place and preserves the order within existing surrogate pairs |
substring(int start) / (int start, int end) | String | No | Returns a String; does not mutate this; throws StringIndexOutOfBoundsException if end > length() or start > end |
charAt(int) / indexOf(String) / length() | char / int | No | charAt requires a valid index. indexOf returns -1 if the substring is absent. length() counts code units. |
toString() | String | No | Converts current buffer contents into a new String |
Tracing insert, delete, and deleteCharAt
StringBuilder sb = new StringBuilder("animals");
sb.insert(7, "-"); // offset == length() (7) is legal -> "animals-"
sb.insert(0, "#"); // "#animals-"
sb.delete(2, 100); // end (100) clamped to length (9) -> "#a"
System.out.println(sb); // Prints: #a
// sb.deleteCharAt(2); // Throws StringIndexOutOfBoundsException (valid: 0..1)
// sb.delete(5, 2); // Throws StringIndexOutOfBoundsException (start > end)
Notice the asymmetric rule between delete and deleteCharAt: sb.delete(0, 100) silently removes everything from 0 to length(), whereas sb.deleteCharAt(sb.length()) immediately fails with StringIndexOutOfBoundsException.
The substring() Return-Type Chaining Trap
Because substring is non-mutating and returns a String (not StringBuilder), check both the changed expression type and the unchanged builder:
StringBuilder sb = new StringBuilder("animals");
String sub = sb.substring(sb.indexOf("a"), sb.indexOf("al")); // "anim"
System.out.println(sb); // Still "animals" (substring did not mutate sb)
System.out.println(sub); // "anim"
// DOES NOT COMPILE: String has no append(String) method
// sb.substring(0, 4).append("X");
Whenever a chained expression includes .substring(...), every call after .substring(...) is invoked on a String, not on the StringBuilder.
StringBuilder.equals() Compares References
Unlike String, StringBuilder does not override Object.equals(Object):
StringBuilder one = new StringBuilder("Java");
StringBuilder two = new StringBuilder("Java");
String str = "Java";
System.out.println(one == two); // false
System.out.println(one.equals(two)); // false (Object.equals)
System.out.println(one.equals(str)); // false (different types)
System.out.println(one.toString().equals(two.toString())); // true
System.out.println(one.toString().equals(str)); // true
// System.out.println(one == str); // DOES NOT COMPILE
Warning
Comparing one == str (StringBuilder == String) fails to compile because the two classes are unrelated siblings (neither is a subtype of the other). However, one.equals(str) compiles cleanly because equals takes Object, and it returns false.
What is the output of the following code?
StringBuilder sb1 = new StringBuilder("clock");
StringBuilder sb2 = sb1.insert(5, "work").delete(2, 99);
sb1.append("oud");
System.out.println(sb1 + " " + sb2 + " " + (sb1 == sb2));
cl cloud false
cloud cloud true
clworkoud clworkoud true
Throws StringIndexOutOfBoundsException at runtime
Which statement about the following code is true?
StringBuilder sb = new StringBuilder(5);
sb.append("hello");
sb.substring(1, 3).append("!");
System.out.println(sb);
Prints h!lo
Prints hello!
Throws StringIndexOutOfBoundsException on line 2
Compilation fails on line 3
What happens when the following code runs?
StringBuilder a = new StringBuilder("Java");
StringBuilder b = new StringBuilder("Java");
System.out.print(a.equals(b) + " ");
System.out.print(a.toString().equals(b.toString()) + " ");
a.deleteCharAt(4);
System.out.print(a);
Prints false true then throws StringIndexOutOfBoundsException
Prints true true Java
Prints false true Java
Compilation fails on a.equals(b)
Sections you finish are checked off in the contents.