Sub topic 5
Length, Capacity and Presizing
This chapter assumes you can already append to a StringBuilder and call toString(). If you can't yet, read the chapter on building strings with StringBuilder first. It also assumes you know that arrays have a fixed size once created. Here you learn the difference between how much text a builder holds and how much room it has reserved. You also learn when reserving room in advance is worth doing.
Two Numbers, Two Meanings
Every StringBuilder reports two sizes:
length()is the number of characters currently stored. It is the length of the string you would get fromtoString().capacity()is the number of characters the internal buffer can hold before it must be replaced by a larger one.
The invariant is length() <= capacity(). The difference between them is spare room that costs memory but no extra work.
StringBuilder sb = new StringBuilder(64);
System.out.println(sb.length()); // 0
System.out.println(sb.capacity()); // 64
sb.append("abc");
System.out.println(sb.length()); // 3The constructor argument is the initial capacity, not an initial length. A new StringBuilder(64) is still empty. Reading sb.charAt(10) on it throws a StringIndexOutOfBoundsException, because index 10 is not below the length.
A StringBuilder is an object wrapping an array. It writes appended characters into the array and keeps a counter of how many slots are in use. length() returns that counter, and capacity() returns the array's size, measured in characters.
What the Constructors Give You
The starting capacity depends on which constructor you call:
| Constructor | Initial length | Initial capacity |
|---|---|---|
| `new StringBuilder()` | 0 | 16 |
| `new StringBuilder(int capacity)` | 0 | the value you pass |
| `new StringBuilder(String str)` | `str.length()` | `str.length() + 16` |
| `new StringBuilder(CharSequence seq)` | `seq.length()` | `seq.length() + 16` |
Passing a negative capacity throws a NegativeArraySizeException. Passing 0 is legal and gives a builder that grows on the first append.
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder("Hello");
System.out.println(a.length() + " " + a.capacity()); // 0 16
System.out.println(b.length() + " " + b.capacity()); // 5 21The 16 extra slots in the String constructor are deliberate headroom, so the first few appends after construction don't trigger growth.
Automatic Growth
When an append would push the length past the capacity, the builder allocates a new, larger array and copies the existing characters into it. The caller sees nothing of this. The old array is left for garbage collection.
In the OpenJDK implementation, the new capacity is normally 2 * oldCapacity + 2. If that is still too small for what you are appending, the builder uses the exact size required instead. The exact growth formula is an implementation detail, not part of the language specification. The documented guarantee is only that the builder grows automatically and that append takes amortized constant time per character. The doubling behavior below is what current OpenJDK releases do, and you can observe it:
public class GrowthTrace {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
int last = sb.capacity();
System.out.println("start -> capacity " + last);
for (int i = 0; i < 100; i++) {
sb.append('x');
if (sb.capacity() != last) {
last = sb.capacity();
System.out.println("length " + sb.length() + " -> capacity " + last);
}
}
}
}On a current OpenJDK this prints:
start -> capacity 16
length 17 -> capacity 34
length 35 -> capacity 70
length 71 -> capacity 142Each reallocation happens on the append that first exceeds the old capacity: the 17th character, then the 35th, then the 71st.
Why Doubling Is Cheap Enough
Growing by a constant factor means the number of reallocations is logarithmic in the final size. The total characters copied across all reallocations is a small multiple of the final length. This is why a StringBuilder in a loop is linear overall, while s += x on a String is quadratic, because every iteration copies everything accumulated so far. Presizing removes the remaining reallocations. It does not change the big-O behavior, so its benefit is a constant factor.
Presizing with a Constructor
If you can estimate the final length, pass it to the constructor. The builder then allocates once and never grows.
import java.util.List;
public class Presize {
public static void main(String[] args) {
List<String> parts = List.of("alpha", "beta", "gamma");
int total = 0;
for (String p : parts) {
total += p.length() + 1; // +1 for the comma
}
StringBuilder sb = new StringBuilder(total);
for (String p : parts) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(p);
}
System.out.println(sb); // alpha,beta,gamma
System.out.println(sb.length()); // 16
System.out.println(sb.capacity()); // 17
}
}The estimate was one character too high, since the last part has no trailing comma. That is fine. A slight overestimate wastes one slot, while a slight underestimate triggers a full reallocation and copy. When the exact size is unknown, err on the high side, but not wildly so.
An Estimate Does Not Have to Be Exact
Sources of a reasonable estimate include:
- The sum of the lengths of known pieces plus separators, as above.
- A typical output size from earlier runs, such as "log lines are usually under 200 characters".
- The size of an input you are transforming, for example
new StringBuilder(input.length() * 2)when each input character produces at most two output characters.
ensureCapacity and trimToSize
You can also adjust capacity after construction.
ensureCapacity(int minimumCapacity) grows the buffer if the current capacity is below the minimum. It does nothing if the capacity is already large enough. It never shrinks the buffer and never changes the length.
StringBuilder sb = new StringBuilder();
sb.ensureCapacity(100);
System.out.println(sb.capacity()); // 100
sb.ensureCapacity(20); // already enough, no change
System.out.println(sb.capacity()); // 100Note that ensureCapacity(100) gives exactly 100 here, not 34. When the requested minimum exceeds the usual doubling result, the builder allocates exactly what you asked for. When the request is only slightly above the current capacity, the doubling formula wins. On a default builder, ensureCapacity(20) produces capacity 34.
trimToSize() does the opposite. It asks the builder to shrink its buffer to fit the current length. The documentation says only that the builder "may" reduce storage, so treat it as a hint.
StringBuilder sb = new StringBuilder(1000);
sb.append("short");
sb.trimToSize();
System.out.println(sb.length()); // 5
System.out.println(sb.capacity()); // typically 5Use trimToSize() when a builder will stay alive for a long time after it is finished growing. For a builder you convert to a String and discard, it is pointless.
setLength: Changing Length Directly
setLength(int newLength) sets the length, with two behaviors:
- If
newLengthis smaller than the current length, the builder keeps the firstnewLengthcharacters and discards the rest. - If
newLengthis larger, the builder pads the end with the null character'\u0000'.
A negative argument throws a StringIndexOutOfBoundsException.
StringBuilder sb = new StringBuilder("Hello, World");
sb.setLength(5);
System.out.println(sb); // Hello
sb.setLength(7);
System.out.println(sb.length()); // 7
System.out.println((int) sb.charAt(6)); // 0The most common use is sb.setLength(0), which empties the builder so it can be reused. A frequent pattern is trimming a trailing separator after a loop:
StringBuilder sb = new StringBuilder();
for (String s : new String[] {"a", "b", "c"}) {
sb.append(s).append(", ");
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 2); // drop the final ", "
}
System.out.println(sb); // a, b, cSetting the length never reallocates to a smaller array. If it grows past the capacity, the buffer grows as usual.
Reuse and Memory Retention
Because setLength(0) keeps the buffer, a reused builder keeps its largest-ever capacity. This is usually what you want in a loop, since later iterations need no growth. It becomes a problem if a long-lived builder, such as a field in a cached object, once held a very large string. The memory stays reserved until you call trimToSize() or drop the builder.
Capacity Does Not Affect the Result
Capacity has no effect on what the builder contains or on the String that toString() returns. toString() copies exactly length() characters into a new, right-sized String. Two builders with the same content but different capacities are indistinguishable once converted.
Consequently, a poor estimate cannot cause wrong output. It can only change how much copying and memory the builder uses.
One more internal detail: since Java 9, strings and builders use compact storage, holding Latin-1 text at one byte per character and switching to two bytes per character when needed. capacity() still counts characters, so you don't need to account for this when presizing. A builder that switches to two-byte storage mid-way uses more memory, which is another reason an accurate estimate helps a little.
Common Mistakes
- Treating the constructor argument as a starting length or as the starting content.
new StringBuilder(5)is empty, not five characters long. - Passing a
charwhere you meant aString.new StringBuilder('A')calls theintconstructor and creates an empty builder with capacity 65, the numeric value of'A'. There is no constructor that takes achar, so this compiles without complaint. - Using
capacity()to test whether a builder is empty. Uselength() == 0. - Presizing with a huge guess "just in case". A large allocation costs time and memory up front, and it is zeroed by the JVM.
- Using
trimToSize()on a builder you are about to append to again. It forces a reallocation on the next growth.
When Presizing Is Worth It
Presizing is a small optimization, not a requirement. Consider it when:
- You build large strings, and the final size is known or easily computed.
- The code runs in a hot path, such as per-request serialization, where garbage and copying add up.
- The estimate is cheap to compute. Walking a large collection just to count characters may cost more than it saves.
Skip it for small strings, one-off messages and code where the builder's contents are unpredictable. Doubling already makes growth cheap, and clear code matters more than shaving a reallocation. If performance does matter, measure with a benchmark harness such as JMH instead of guessing, because the JIT compiler and allocator behavior vary by version.
Summary of the API
| Method | Effect on length | Effect on capacity |
|---|---|---|
| `append(...)` | grows by the appended amount | grows automatically if needed |
| `setLength(n)` | becomes `n` (truncates or pads with `'\u0000'`) | grows if `n` exceeds it, never shrinks |
| `ensureCapacity(n)` | unchanged | grows to at least `n` if smaller |
| `trimToSize()` | unchanged | may shrink to fit the length |
| `toString()` | unchanged | unchanged |
Exercise
You run StringBuilder sb = new StringBuilder("Java"); and then sb.append(" builders rock");. What are length() and capacity() after the construction, and does the append force a reallocation? The appended text is 14 characters long.
Show answer
After construction, length is 4 and capacity is 20 (4 + 16). The append makes the length 18, which is still at most 20, so no reallocation occurs. The final length is 18 and the capacity is still 20.
Exercise
A method receives an array of 1,000 words, each at most 12 characters long, and joins them with single spaces. Write the line that creates a StringBuilder presized so the join never reallocates, and explain how you chose the number.
Show answer
StringBuilder sb = new StringBuilder(1000 * 12 + 999); There are at most 1,000 12 word characters plus 999 spaces between 1,000 words, which gives 12,999 characters. Using `1000 13` is also acceptable as a slight overestimate. Either way the builder never needs to grow.
Exercise
What does this code print, and why? StringBuilder sb = new StringBuilder("abcdef"); sb.setLength(3); sb.append("XY"); System.out.println(sb + " " + sb.length() + " " + sb.capacity());
Show answer
It prints abcXY 5 22. The constructor gives capacity 6 + 16 = 22. setLength(3) truncates the content to "abc" without shrinking the buffer. Appending "XY" brings the length to 5, which fits, so the capacity stays 22.