Home Java StringBuilder Methods getChars() Java StringBuilder getChars() Method 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.
StringBuilder sb = new StringBuilder("HelloJava");
char[] buf = new char[4];
sb.getChars(5, 9, buf, 0); // buf becomes {'J', 'a', 'v', 'a'} Call What 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.lang.StringBuilder
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Parameters Parameter Description 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 Value Description voidReturns nothing; copies directly into dst.
Important
getChars() returns void and cannot be chained. Passing a null destination array throws NullPointerException. Any invalid index—srcBegin < 0, dstBegin < 0, srcBegin > srcEnd, srcEnd > length(), or dstBegin + (srcEnd - srcBegin) > dst.length—throws IndexOutOfBoundsException.
Compare with Similar Methods Copying characters out of a StringBuilder:
Java Examples 1. Copy into char[] buffer 2. Pack two builders 3. Bounds and null errors 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().
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));
}
} Array: [4, 0, 9, 2]
String: 4092 How It Works Pre-size buffer. Copying indexes 6..10 needs four slots, matching new char[4].Copy without String allocation. getChars(6, 10, code, 0) writes '4', '0', '9', and '2' directly into code.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.
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]);
}
} [Java:2026]
Length = 11, first slot = J How It Works Fixed frame array. The brackets and colon stay untouched at indexes 0, 5, and 10.Write at different offsets. first writes into indexes 1..4 via dstBegin = 1, while second writes into 6..9 via dstBegin = 6.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.
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");
}
}
} Small destination threw IndexOutOfBoundsException
Null destination threw NullPointerException How It Works Overflow check. Copying five chars into a 3-char array exceeds small.length and throws IndexOutOfBoundsException.Null array rejected. Passing null as dst immediately raises NullPointerException.Builder unchanged. Neither failed copy alters sb.Frequently Asked Questions What does StringBuilder getChars() return? It has a void return type. Instead of returning an array, it copies characters directly into the char[] dst array you pass in.
Why use getChars() instead of toString().toCharArray()? getChars() lets you copy just a subrange and reuse an existing char[] buffer without allocating a new String or array.
Is srcEnd inclusive or exclusive in getChars()? srcBegin is inclusive and srcEnd is exclusive, copying exactly srcEnd - srcBegin characters.
When does getChars() throw IndexOutOfBoundsException? When srcBegin < 0, dstBegin < 0, srcBegin > srcEnd, srcEnd > sb.length(), or dstBegin + (srcEnd - srcBegin) > dst.length.
What happens if dst is null in getChars()? It throws NullPointerException.
Next: indexOf() Find the starting index of the first matching String substring, or -1 if absent.
indexOf() tutorial → About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion