Java StringBuilder getChars() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition

In Java, sb.getChars(srcBegin, srcEnd, dst, dstBegin) copies characters from index srcBegin (inclusive) to srcEnd (exclusive) of a StringBuilder directly into an existing char[] array dst starting at dstBegin.

Because it writes into an array you already own and returns void, it avoids allocating a brand-new String or char[] like sb.toString().toCharArray() does.

An instance method of the java.lang.StringBuilder class (since Java 1.5, JDK 1.5): a final, mutable sequence of UTF-16 characters that is not thread-safe. Call it on an existing builder, as in sb.getChars(...). No import is needed because java.lang is always visible.

Syntax

Pass the source range in the builder, the destination char[], and the destination offset.

Java
StringBuilder sb = new StringBuilder("HelloJava");
char[] buf = new char[4];
sb.getChars(5, 9, buf, 0);   // buf becomes {'J', 'a', 'v', 'a'}
CallWhat it does
sb.getChars(0, sb.length(), arr, 0)Copies the entire builder into arr starting at index 0.
sb.getChars(2, 5, arr, 3)Copies 3 chars from sb into arr[3..5].
sb.toString().toCharArray()Simpler alternative when allocating a fresh char[] is fine.

Always ensure dst has at least dstBegin + (srcEnd - srcBegin) elements before calling getChars().

Library declarations
Java
// java.lang.StringBuilder
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Parameters

ParameterDescription
srcBegin (int)Inclusive start index in the builder (>= 0).
srcEnd (int)Exclusive end index in the builder (srcBegin <= srcEnd <= length()).
dst (char[])Non-null destination array.
dstBegin (int)Starting index in dst where the copied chars are written.

Return Value

Return ValueDescription
voidReturns nothing; copies directly into dst.

Compare with Similar Methods

Copying characters out of a StringBuilder:

MethodHow it differs
substring(start, end)Creates a new String instead of filling a char[].
toString()Copies the whole builder to a String (pair with toCharArray() for a fresh array).
append(char[], offset, len)Reverse direction: copies from a char[] into a StringBuilder.
Arrays.toString(arr)Formats a char[] cleanly for console inspection.

Java Examples

Example 1 — Copy a Slice Into a Reusable char[] Buffer

Extract a slice from a StringBuilder into a pre-allocated char[] and format it with Arrays.toString().

Java
import java.util.Arrays;

public class StringBuilderGetCharsBuffer {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Order-4092-OK");
        char[] code = new char[4];

        sb.getChars(6, 10, code, 0);
        System.out.println("Array:  " + Arrays.toString(code));
        System.out.println("String: " + new String(code));
    }
}

How It Works

  1. Pre-size buffer. Copying indexes 6..10 needs four slots, matching new char[4].
  2. Copy without String allocation. getChars(6, 10, code, 0) writes '4', '0', '9', and '2' directly into code.
  3. Inspect result. Arrays.toString prints every character element, and new String(code) shows 4092.

Example 2 — Combine Slices From Two Builders Into One char[]

Use dstBegin to place characters from two separate StringBuilder instances side by side in a single array.

Java
import java.util.Arrays;

public class StringBuilderGetCharsCombine {
    public static void main(String[] args) {
        StringBuilder first = new StringBuilder("Java");
        StringBuilder second = new StringBuilder("2026");

        char[] frame = {'[', '-', '-', '-', '-', ':', '-', '-', '-', '-', ']'};
        first.getChars(0, 4, frame, 1);
        second.getChars(0, 4, frame, 6);

        System.out.println(new String(frame));
        System.out.println("Length = " + frame.length + ", first slot = " + Arrays.copyOf(frame, 5)[1]);
    }
}

How It Works

  1. Fixed frame array. The brackets and colon stay untouched at indexes 0, 5, and 10.
  2. Write at different offsets. first writes into indexes 1..4 via dstBegin = 1, while second writes into 6..9 via dstBegin = 6.
  3. In-place packing. The final frame reads [Java:2026] without intermediate string concatenation.

Example 3 — Catch Small-Buffer Bounds Errors and null Destinations

See what happens when dst has too little room or is null.

Java
public class StringBuilderGetCharsErrors {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        char[] small = new char[3];

        try {
            sb.getChars(0, 5, small, 0);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Small destination threw IndexOutOfBoundsException");
        }

        try {
            sb.getChars(0, 2, null, 0);
        } catch (NullPointerException e) {
            System.out.println("Null destination threw NullPointerException");
        }
    }
}

How It Works

  1. Overflow check. Copying five chars into a 3-char array exceeds small.length and throws IndexOutOfBoundsException.
  2. Null array rejected. Passing null as dst immediately raises NullPointerException.
  3. Builder unchanged. Neither failed copy alters sb.

Frequently Asked Questions

It has a void return type. Instead of returning an array, it copies characters directly into the char[] dst array you pass in.
getChars() lets you copy just a subrange and reuse an existing char[] buffer without allocating a new String or array.
srcBegin is inclusive and srcEnd is exclusive, copying exactly srcEnd - srcBegin characters.
When srcBegin < 0, dstBegin < 0, srcBegin > srcEnd, srcEnd > sb.length(), or dstBegin + (srcEnd - srcBegin) > dst.length.
It throws NullPointerException.

Next: indexOf()

Find the starting index of the first matching String substring, or -1 if absent.

indexOf() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful