Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How does StringBuilder grow its buffer, and what are the consequences for building very large strings, such as a 500 MB report?

A StringBuilder starts with a capacity of 16 characters, or the initial string's length plus 16, and when an append does not fit it allocates a new array of about twice the old capacity plus two and copies everything across. For a 500 MB report that means the old and the new array exist at the same moment during each growth, and toString() makes one more full copy, so peak memory can reach about three times the final size. Arrays also have a hard limit of a little under Integer.MAX_VALUE elements, and a single non-Latin-1 character doubles the bytes needed, so very large output should be streamed to a Writer instead of built as one String.

Why this question is asked

Most of the time we never think about how a StringBuilder grows, and that is fine. It starts to matter when someone builds a very large export, a report, a CSV dump or a big JSON document, in memory, and the service dies with OutOfMemoryError although the heap seemed big enough. Interviewers ask this to see whether we can reason about peak memory, not just final size. In this answer, we will see how the buffer grows, calculate the peak for a 500 MB report, look at the array size limit and the effect of compact strings, and then fix the design by streaming.

1A Quick Recap of How the Buffer Grows

A StringBuilder keeps its characters in an internal array that is usually larger than the text it holds. The size of that array is its capacity; length() is how much of it is used. new StringBuilder() starts with capacity 16, and new StringBuilder("hello") starts with 5 + 16 = 21.

When an append needs more room than the capacity, the builder computes a new capacity, normally the old capacity times two plus two, or the needed length if that is larger, allocates a new array of that size, copies the old contents into it and drops the old array.

Java
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); // 16
sb.append("x".repeat(17));
System.out.println(sb.capacity()); // 34 = 16 * 2 + 2
sb.append("y".repeat(20));
System.out.println(sb.capacity()); // 70 = 34 * 2 + 2
System.out.println(new StringBuilder("hello").capacity()); // 21 = 5 + 16

Doubling means the number of growth steps is small, about 25 to reach hundreds of millions, and the total copying stays linear in the final size. So growth is not a speed problem. It is a peak memory problem.

2Peak Memory for a 500 MB Report

Take a report of 500 million characters, all Latin-1, so with compact strings each character takes one byte. Near the end, the builder's capacity is around 270 million and has to grow. At that moment, the old array of about 270 MB is still live, because its contents are being copied, and the new array of about 540 MB has just been allocated. That is about 810 MB at once.

When the builder finishes, we call toString(), which copies the content into a new String of exactly 500 MB, while the builder's 540 MB array is still reachable. Now we are at about 1,040 MB. So a 500 MB result needs roughly two to three times its size at the peak, depending on where the final growth step lands.

Memory at each moment while building 500 million Latin-1 chars
MomentArrays aliveTotal
Just before the last growthbuilder array of about 270 MBabout 270 MB
During the last growth (copy)old 270 MB + new 540 MBabout 810 MB
During toString()builder 540 MB + String 500 MBabout 1,040 MB
After the builder is droppedString 500 MB500 MB
Figures are approximate; with UTF-16 content every number doubles.

Notice that a heap of 1 GB looks large enough for a 500 MB report, and it is not. And the large arrays are humongous objects for G1, allocated in contiguous regions, so fragmentation can cause an OutOfMemoryError even when the total free space looks sufficient.

3The Array Size Limit

Java arrays are indexed by int, so no array can have more than Integer.MAX_VALUE elements, and in practice the JVM's limit is slightly lower, a few elements under that value. For a StringBuilder with Latin-1 content, the byte array holds one byte per character, so the limit is a little over 2 billion characters. With UTF-16 content, two bytes per character, the limit is about 1 billion characters.

When growth would exceed the limit, or when the heap cannot provide an array that large, the builder fails with OutOfMemoryError. The message varies by situation and version, for example Java heap space or Requested array size exceeds VM limit, so check what your JDK reports. Either way, no amount of tuning makes a single String of several billion characters practical.

4Compact Strings and Inflation

Since JDK 9, a StringBuilder, like a String, starts in Latin-1 mode, one byte per character. If we append a character outside Latin-1, such as an emoji or a Chinese character, the builder inflates: it allocates a new array twice as big in bytes and converts every existing character to two bytes. From then on, everything costs two bytes per character.

For our report, that means a single curly quote copied from a product description, U+201C, which is outside Latin-1, at position 400 million turns a 400 MB buffer into an 800 MB one in one step, while the old buffer is still alive for the copy. Peak memory then doubles compared with our calculation, all because of one character.

Java
StringBuilder sb = new StringBuilder(10);
sb.append("abc"); // Latin-1: 1 byte per char internally
sb.append('“'); // a left double quote, not Latin-1: the whole buffer inflates to UTF-16
sb.append("def"); // now 2 bytes per char for everything
System.out.println(sb.length()); // 7: length counts chars, not bytes

5The Fix: Stream the Output

The real fix is to avoid holding the whole report in memory. A report is written row by row anyway, so we write each row to a Writer as soon as it is ready: to a file, to an HTTP response or to object storage. Memory then stays at the size of a buffer, typically 8 KB, plus one row, whatever the report's size.

Java
// Before: builds 500 MB in memory, peaks above 1 GB
StringBuilder sb = new StringBuilder();
for (Row r : rows) sb.append(format(r)).append('\n');
Files.writeString(target, sb.toString());
// After: constant memory
try (BufferedWriter w = Files.newBufferedWriter(target, StandardCharsets.UTF_8)) {
for (Row r : rows) { // rows can come from a streaming query or a cursor
w.write(format(r));
w.newLine();
}
}
// In a Spring MVC controller, the same idea for an HTTP download
@GetMapping("/report.csv")
StreamingResponseBody report() {
return out -> {
Writer w = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
for (Row r : reportService.rows()) { w.write(format(r)); w.write('\n'); }
w.flush();
};
}

Notice that the source of the rows should stream as well, for example a JDBC cursor with a fetch size or a Stream returned by a repository, otherwise we have only moved the memory problem. If a builder is truly needed for moderately large text, say 20 MB, we pre-size it with new StringBuilder(expected) or ensureCapacity, so there is one allocation and no growth copies.

6Follow-up questions

Why does the growth formula add two?

It makes sure an empty or very small builder grows to a useful size even when the old capacity is zero, since zero times two is still zero. It is a detail of the implementation; what matters is that growth is roughly doubling.

Does trimToSize() help with the peak?

No. trimToSize() shrinks the builder's array to its length after the fact, which can save memory if the builder lives on, but the peak already happened during growth. For large output, streaming or pre-sizing is what lowers the peak.

7Conclusion

In this answer, we saw that a StringBuilder starts at 16 characters, or the initial length plus 16, and grows to about twice its capacity plus two by allocating and copying. For a 500 MB report, the old and new arrays during the last growth plus the extra copy made by toString() push peak memory to roughly two to three times the final size. Arrays are capped a little under Integer.MAX_VALUE elements, and one non-Latin-1 character inflates the whole buffer to two bytes per character. The design fix is to stream rows to a Writer, from a streaming source, and to pre-size a builder only for moderately large text.

What to say in the interviewAbout 90 seconds aloud

Open with

A StringBuilder keeps its characters in an array with spare capacity: 16 by default, or the initial string's length plus 16. When an append does not fit, it allocates a new array of about double the old capacity plus two and copies everything across.

Then, if they want more

That keeps total copying linear, so speed is fine, but peak memory is the issue.

For a 500 MB report, at the last growth step the old array of around 270 MB and the new one of around 540 MB are alive together, and then toString makes a full 500 MB copy while the builder is still referenced, so we can need around a gigabyte or more for a 500 MB result.

Since JDK 9 the builder is one byte per character while everything is Latin-1, but a single character outside Latin-1, say a curly quote, inflates the whole buffer to two bytes per character, which doubles all of those numbers.

On top of that, arrays are limited to a bit under Integer.MAX_VALUE elements, so beyond about two billion Latin-1 characters, or one billion UTF-16, it fails with OutOfMemoryError regardless of heap size. So for something like a 500 MB report I would not build a String at all.

I would stream rows from a cursor straight to a BufferedWriter, a file or a StreamingResponseBody in Spring, so memory stays at the size of a buffer and one row.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does StringBuilder grow its buffer, and what are the consequences for building very...": https://scrivio-interview-library.netlify.app/java/strings/25c672d7e3/