Builder: StringBuilder's capacity grows automatically

The constructor argument only sets an initial capacity hint to avoid early resizing; append() still grows the internal array on demand once more room is needed. Staying under the initial capacity means no resize happens at all.

Code
StringBuilder sb = new StringBuilder(64);
System.out.println("Initial capacity: " + sb.capacity());
sb.append("just a short string");
System.out.println("Length after append: " + sb.length());
System.out.println("Capacity still covers it, no resize needed: " + (sb.capacity() >= sb.length()));
Output
Initial capacity: 64
Length after append: 19
Capacity still covers it, no resize needed: true
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms