Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

StringBuilder — a mutable text buffer

StringBuilder lets you build and modify text incrementally. Learn the difference between length and capacity, and what happens when setLength truncates or extends the sequence.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new StringBuilder();
new StringBuilder(8);
int length();
int capacity();
void setLength(int newLength);

java.lang.StringBuilder is a mutable character sequence. append adds content, and toString() creates the resulting String. The class provides no synchronization guarantee; do not share a mutable instance between threads without appropriate synchronization.

StringBuilder() creates an empty buffer with capacity 16. StringBuilder(int) creates an empty buffer with the specified capacity; a negative value causes NegativeArraySizeException. Initial capacity is not text length.

StringBuilder.length() returns the number of UTF-16 char units in the content, not necessarily the number of user-visible characters. StringBuilder.capacity() measures room for those units, including positions already occupied. Capacity grows automatically when more room is needed.

StringBuilder.setLength(int) returns void: a smaller length truncates the end, while a larger length appends zero-valued characters ('\u0000'), not spaces. A negative length causes IndexOutOfBoundsException. setLength(0) removes all logical content; do not treat this as secure erasure of data from memory.

Examples

public class Main {
    public static void main(String[] args) {
        StringBuilder defaults = new StringBuilder();
        System.out.println(defaults.length() + ":" + defaults.capacity());

        StringBuilder text = new StringBuilder(8);
        text.append("Java");
        System.out.println(text.length() + ":" + text.capacity());

        text.setLength(2);
        System.out.println(text.toString());

        text.setLength(4);
        System.out.println(text.length() + ":" + (int) text.charAt(2));

        text.setLength(0);
        System.out.println(text.length());
    }
}

Result

0:16
4:8
Ja
4:0
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources