StringBuilder Capacity Grows And Trims

StringBuilder starts at capacity 16, doubles plus two on overflow via ensureCapacity, and trimToSize hands the unused tail back when appending is done.

JavaResilience

Code

snippet
public class CapacityLifecycle {

    public static void main(String[] args) {
        // 无参构造:初始容量 16(javadoc 明文)
        StringBuilder sb = new StringBuilder();
        System.out.println("initial capacity: " + sb.capacity());

        // append 不超容量时零分配;溢出后内部缓冲自动扩容,无异常路径
        sb.append("audit-log-2026");
        System.out.println("after append: length=" + sb.length() + " capacity=" + sb.capacity());

        // ensureCapacity:新容量取 minCapacity 与 2*旧容量+2 的较大者
        sb.ensureCapacity(50);
        System.out.println("ensureCapacity(50): " + sb.capacity());

        // 容量只是缓冲大小,内容不受影响
        System.out.println("content: " + sb);

        // trimToSize:尝试把多余空间还回去(文档写明 may, but is not required to)
        sb.trimToSize();
        System.out.println("after trim: capacity=" + sb.capacity());
    }
}

How the snippet works

StringBuilder Capacity Grows And Trims reduces to the class CapacityLifecycle and the function main.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The one signature that matters here is public static void main(String[] args)

The run prints labeled output — initial capacity:, after append: length=, ensureCapacity(50): — when the file runs.

Key statements worth quoting

StringBuilder sb = new StringBuilder();
sb.append("audit-log-2026");
sb.ensureCapacity(50);

Interactive Tools for This Topic

FAQ

What does StringBuilder Capacity Grows And Trims print when run?
No setup needed: run the file and look for labeled lines like `initial capacity:`, `after append: length=`, `ensureCapacity(50):` in the output.