Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

StringBuilder: capacity, snapshots, and buffer reuse

Size a mutable text buffer, save immutable results, and keep buffers separate across workers. Use explicit formatting to emit exactly two hexadecimal digits per byte.

Version: Java SE 21

Syntax

StringBuilder(int capacity)
StringBuilder append(String str)
StringBuilder append(int i)
StringBuilder append(char c)
String toString()
void setLength(int newLength)
int length()       // StringBuilder and String
int capacity()     // StringBuilder

In Java SE 21, StringBuilder(int) in java.lang creates an empty builder: length() starts at 0, while capacity() reports the initial space in UTF-16 code units. Capacity is not a length limit; the builder grows as needed. A negative capacity throws NegativeArraySizeException.

In the StringBuilder.append/toString pattern, append(String) adds text (a null argument of type String adds null), append(int) adds decimal digits with a minus sign when needed, and append(char) adds one code unit. Each returns the same builder for chaining. toString() captures the current contents as an immutable String that later edits cannot change.

In StringBuilder.setLength/append/toString, start with setLength(0) to clear the logical contents before building the next result. This is neither a request to shrink capacity nor a secure erase. Shortening preserves the prefix, extending pads with U+0000, and a negative length throws IndexOutOfBoundsException. StringBuilder is not thread-safe: each worker builds four rows in its own buffer, and the main thread reads the resulting strings after join().

For hex without separators, each byte takes exactly two digits. Math.multiplyExact(bytes.length, 2) computes the initial capacity and throws ArithmeticException if the result does not fit in an int. Byte.toUnsignedInt gives a value from 0 to 255; the high and low four bits each select one lowercase hex digit. The result's String.length() counts UTF-16 code units, not input bytes.

Examples

public class BuilderDemo {
    private static final String HEX = "0123456789abcdef";

    private static void writeRows(String worker, String[] rows) {
        StringBuilder line = new StringBuilder(8);
        for (int i = 0; i < rows.length; i++) {
            line.setLength(0);
            rows[i] = line.append(worker).append(":").append(i + 1).toString();
        }
    }

    private static String toHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder(Math.multiplyExact(bytes.length, 2));
        for (byte b : bytes) {
            int value = Byte.toUnsignedInt(b);
            hex.append(HEX.charAt(value >>> 4));
            hex.append(HEX.charAt(value & 0x0f));
        }
        return hex.toString();
    }

    public static void main(String[] args) throws InterruptedException {
        String[] aRows = new String[4];
        String[] bRows = new String[4];
        Thread a = new Thread(() -> writeRows("A", aRows));
        Thread b = new Thread(() -> writeRows("B", bRows));
        a.start();
        b.start();
        a.join();
        b.join();

        for (String row : aRows) System.out.println(row);
        for (String row : bRows) System.out.println(row);
        String hex = toHex(new byte[] {0x00, 0x0f, (byte) 0xa5, (byte) 0xff});
        System.out.println("hex=" + hex + ", length=" + hex.length());
    }
}

Result

A:1
A:2
A:3
A:4
B:1
B:2
B:3
B:4
hex=000fa5ff, length=8

Each worker reuses one builder for four rows. After `join()`, the main thread prints A's rows before B's, regardless of scheduling. The four bytes produce `000fa5ff` with length `8`.

Related lessons

  • Java · Lesson 28 · Advanced · Version: 2
  • Java · Lesson 35 · Advanced · Version: 2
  • Java · Lesson 62 · Advanced · Version: 2

Sources