Sub topic 5
Length, Capacity and Presizing
This chapter assumes that you know basic Java syntax, loops, methods, and the difference between an object and a primitive. You should also know that String objects cannot be changed after creation.
Length and Capacity Mean Different Things
A StringBuilder stores characters in a growable internal buffer. Two measurements describe that buffer:
length()is the number of characters currently stored.capacity()is the number of characters the current buffer can hold before it must grow.
Capacity is not the same as the number of bytes used in memory. Java stores StringBuilder text as UTF-16 character data. For this API, the useful unit is the number of char values that can fit, not a byte count.
A new builder has a length of zero. Its default capacity is 16:
public class CapacityDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println("length: " + sb.length());
System.out.println("capacity: " + sb.capacity());
sb.append("Java");
System.out.println("length: " + sb.length());
System.out.println("capacity: " + sb.capacity());
}
}The output is:
length: 0
capacity: 16
length: 4
capacity: 16Appending text changes the length. It does not necessarily change the capacity because the existing buffer may already have enough room.
Why Capacity Matters
When a builder becomes too small, Java allocates a larger buffer and copies the existing characters into it. This preserves the builder's contents, but the allocation and copy take time.
The capacity growth formula is designed to make growth less frequent. When more room is needed, the new capacity is generally based on twice the old capacity plus two, unless even more space is required immediately. You should not write code that depends on the exact growth sequence. The important fact is that capacity grows automatically and may be larger than the current length.
| Expression | Meaning |
|---|---|
| `sb.length()` | Characters currently stored |
| `sb.capacity()` | Characters the current buffer can hold |
| `sb.ensureCapacity(n)` | Request room for at least `n` characters |
| `sb.trimToSize()` | Reduce capacity toward the current length |
Presizing a Builder
If you can estimate the final size of the text, pass an initial capacity to the constructor:
public class PresizingDemo {
public static void main(String[] args) {
int expectedCharacters = 1_000;
StringBuilder sb = new StringBuilder(expectedCharacters);
for (int i = 1; i <= 100; i++) {
sb.append("Record: ").append(i).append('\n');
}
System.out.println("length: " + sb.length());
System.out.println("capacity: " + sb.capacity());
}
}The integer passed to new StringBuilder(...) is the initial capacity. It is not a limit. If the builder needs more space, it grows normally.
Presizing helps most when all of these conditions are true:
- The builder receives many appends.
- The final size is large.
- You can make a reasonable size estimate.
- The builder is created often enough for allocation costs to matter.
A rough estimate is still useful. For example, if every record is about 40 characters and you expect 10,000 records, an initial capacity near 400,000 characters may reduce growth. Do not reserve enormous amounts of memory for a vague estimate. A capacity that is much larger than needed consumes memory even if those characters are never appended.
You can also request additional capacity after construction:
public class EnsureCapacityDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.ensureCapacity(100);
System.out.println(sb.length()); // 0
System.out.println(sb.capacity()); // at least 100
sb.append("Ready");
System.out.println(sb);
}
}ensureCapacity does not add spaces or placeholder characters. It only prepares storage. The length remains zero until you append text.
When to Trim
After construction is complete, trimToSize() can reduce unused capacity:
StringBuilder sb = new StringBuilder(10_000);
sb.append("small result");
System.out.println(sb.length()); // 12
System.out.println(sb.capacity()); // 10000
sb.trimToSize();
System.out.println(sb.capacity()); // close to 12Trimming can save memory when the builder will remain alive for a long time. It can hurt performance if you plan to append more text soon, because later appends may force the buffer to grow again. Avoid trimming as a routine step inside a loop.
Exercise
Exercise
A builder starts with capacity 16. You append 10 characters, call ensureCapacity(50), and append 20 more characters. What can you conclude about its final length and capacity?
Show answer
Its final length is 30. Its capacity is at least 50, although the exact value may be larger because the builder's growth rules can reserve extra space.