CKTIS / Java
StringBuilder: initial capacity, length, and buffer growth
Distinguish buffer capacity from text length, chain append calls, and check that the buffer has grown without relying on a specific final capacity.
Version: Java SE 21
Syntax
java.lang.StringBuilder
public StringBuilder()
public StringBuilder(int capacity)
public StringBuilder append(String str)
public StringBuilder append(int i)
public String toString()
public int capacity()
public int length()In Java SE 21, java.lang.StringBuilder holds mutable text. StringBuilder() starts empty with capacity 16; StringBuilder(int) starts empty with exactly the requested capacity. Both start with length 0. A negative capacity throws NegativeArraySizeException.
The following distinctions explain StringBuilder.append/toString/capacity/length. length() counts the UTF-16 code units (char values) currently stored, not Unicode code points. capacity() counts how many code units fit in the current buffer in total, including those already stored. It is neither the number of free slots nor a size in bytes. If an append would exceed that capacity, the buffer grows automatically.
append(String) adds text at the end; a String argument whose value is null adds "null". append(int) adds the decimal representation of the integer, not a character with that code. Both overloads modify and return the same builder, so calls can be chained.
toString() returns an immutable String containing the current text. Later edits to the builder do not change that result. If you can estimate the final length, choosing an initial capacity can reduce reallocations; that capacity is not a length limit.
Examples
public class Main {
public static void main(String[] args) {
StringBuilder defaults = new StringBuilder();
StringBuilder text = new StringBuilder(4);
System.out.println("default: capacity=" + defaults.capacity()
+ ", length=" + defaults.length());
System.out.println("initial: capacity=" + text.capacity()
+ ", length=" + text.length());
text.append("ID=").append(123);
String result = text.toString();
int length = text.length();
if (text.capacity() < length) {
throw new AssertionError("capacity < length");
}
System.out.println("text=" + result);
System.out.println("length=" + length);
System.out.println("capacity >= length: true");
}
}Result
default: capacity=16, length=0 initial: capacity=4, length=0 text=ID=123 length=6 capacity >= length: true
Both builders start at length 0. The second starts with capacity exactly 4. The chain appends `ID=` and `123`, and `toString()` returns `ID=123`, with length 6. The buffer had to grow; the check requires only `capacity() >= length()` and does not assume a specific capacity after growth.
Related lessons
- Java · Lesson 49 · Advanced · Version: 2