Builder: StringBuilder.setLength truncates or pads the buffer

Passing a length shorter than the current one truncates the buffer immediately, while a longer length pads it with null characters up to that length. Either way it changes length() directly without creating a new object.

Code
StringBuilder sb = new StringBuilder("Hello world");
sb.setLength(5);
System.out.println("Truncated: " + sb);
sb.setLength(8);
System.out.println("Padded length: " + sb.length());
Output
Truncated: Hello
Padded length: 8
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