Java String getChars(): In-Place Character Array Extraction

The String.getChars() method copies characters from a specified range of a string into a destination char[] array.

Zero-Allocation Slicing & Memory Efficiency: Unlike substring() or toCharArray() which allocate fresh objects on the heap, getChars() writes directly into an existing buffer. To convert a character array back into a string, see copyValueOf() and valueOf(). For byte encoding, see getBytes(), or measure string size with length().

1. Syntax & Parameter Specifications 🔝

The getChars() method takes four parameters to control extraction coordinates and destination offsets:

 // Formal signature of String.getChars() in java.lang.String
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Parameter Type Description & Operational Rule
srcBegin int The 0-based index of the first character in the string to copy.
srcEnd int The index after the last character in the string to copy (exclusive).
dst char[] The destination character array where characters are written.
dstBegin int The starting offset within the destination array where copying begins.

2. Basic getChars() Usage Examples 🔝

Extracting a 3-character range (indices 2 through 4) and placing them at offset 2 in a 5-element array:

String my_str = "Welcome to plus2net";

 // Destination array with 5 slots
char[] my_array = new char[5];

 // Copy characters from index 2 to 5 ("lco") into destination starting at offset 2
my_str.getChars(2, 5, my_array, 2);

System.out.println("Array contents: [" + new String(my_array) + "]");
for (int i = 0; i < my_array.length; i++) {
    System.out.println("my_array[" + i + "] = '" + my_array[i] + "'");
}

Terminal Output:

Array contents: [  lco]
my_array[0] = ''
my_array[1] = ''
my_array[2] = 'l'
my_array[3] = 'c'
my_array[4] = 'o'

3. Copying Entire Strings into a Character Array 🔝

To transfer the full content of a string into an array, pass 0 as srcBegin and length() as srcEnd:

String message = "Java 2026";
char[] dest = new char[message.length()];

 // Copying entire string into a char array
message.getChars(0, message.length(), dest, 0);

System.out.println("Copied message: " + String.valueOf(dest));

Terminal Output:

Copied message: Java 2026

4. Comparison: getChars() vs. toCharArray() vs. substring() 🔝

Selecting the right extraction method based on allocation and performance goals:

Method Return Type Heap Allocation Primary Use Case
str.getChars(...) void (in-place) Zero heap allocation High-throughput parsers, reusable memory buffers, stream IO.
str.toCharArray() char[] Allocates new char[] Convenient whole-string character access.
str.substring(...) String Allocates new String Standard text slicing where a String object is required.

5. Boundary Constraints & IndexOutOfBoundsException 🔝

Java enforces strict boundary conditions on both source coordinates and destination array capacities:

String my_str = "Welcome to plus2net";
char[] my_array = new char[5];

 // RISKY: dstBegin = 4 with 3 characters to copy (4 + 3 = 7 > array length 5)
try {
    my_str.getChars(2, 5, my_array, 4);
} catch (StringIndexOutOfBoundsException e) {
    System.out.println("Caught exception: destination buffer overflow!");
}

Terminal Output:

Caught exception: destination buffer overflow!

Source coordinates must satisfy 0 <= srcBegin <= srcEnd <= length():

String my_str = "plus2net";
char[] dest = new char[10];

 // ERROR 1: srcBegin > srcEnd
try {
    my_str.getChars(4, 2, dest, 0);
} catch (IndexOutOfBoundsException e) {
    System.out.println("Caught: srcBegin > srcEnd!");
}

 // ERROR 2: srcEnd > string length
try {
    my_str.getChars(0, 15, dest, 0);
} catch (IndexOutOfBoundsException e) {
    System.out.println("Caught: srcEnd > length!");
}

Terminal Output:

Caught: srcBegin > srcEnd!
Caught: srcEnd > length!

6. Production Recipe: Reusable Buffer Splicer 🔝

Assembling multi-part identifier strings into a single destination character array without intermediate string concatenation:

public class BufferSplicer {
    public static void main(String[] args) {
        String prefix = "USR-";
        String id = "98765";
        String suffix = "-PROD";

         // Total length = 4 + 5 + 5 = 14 chars
        char[] fullBuffer = new char[14];

         // Splice all three strings into one reusable buffer without heap allocations
        prefix.getChars(0, prefix.length(), fullBuffer, 0);
        id.getChars(0, id.length(), fullBuffer, 4);
        suffix.getChars(0, suffix.length(), fullBuffer, 9);

        System.out.println("Spliced Buffer: " + new String(fullBuffer));
    }
}

Terminal Output:

Spliced Buffer: USR-98765-PROD

7. Practical Recipe: Zero-Allocation Fast Tokenizer 🔝

Processing stream tokens repeatedly through a fixed, reusable character buffer to eliminate garbage collector churn:

public class FastTokenizer {
    private final char[] reusableBuffer = new char[32];

    public void processToken(String data, int start, int end) {
        int count = end - start;
        if (count <= reusableBuffer.length) {
             // Direct zero-allocation copy into buffer
            data.getChars(start, end, reusableBuffer, 0);
            System.out.println("Processed: " + new String(reusableBuffer, 0, count));
        }
    }

    public static void main(String[] args) {
        FastTokenizer tokenizer = new FastTokenizer();
        String stream = "GET /api/v1/users HTTP/1.1";
        tokenizer.processToken(stream, 0, 3);    // GET
        tokenizer.processToken(stream, 4, 17);   // /api/v1/users
    }
}

Terminal Output:

Processed: GET
Processed: /api/v1/users

8. Common Developer Pitfalls & Traps 🔝

Destination Array Capacity Overflow

Always check that dstBegin + (srcEnd - srcBegin) <= dst.length. Attempting to write past the end of the destination array triggers a runtime StringIndexOutOfBoundsException.

Passing Null Array or Inverted Coordinates

Passing dst = null raises a NullPointerException. Passing srcBegin > srcEnd raises an IndexOutOfBoundsException.

9. Complete Compilable Java Program 🔝

You can compile and run this complete verification class locally in any Java IDE or environment:

public class StringGetCharsFullDemo {
    public static void main(String[] args) {
        String source = "plus2net tutorial";
        char[] buffer = new char[8];

         // 1. Copy exact slice "plus2net"
        source.getChars(0, 8, buffer, 0);
        if (new String(buffer).equals("plus2net")) {
            System.out.println("Check 1 Passed: Exact string slice copied into array.");
        }

         // 2. Verify partial insertion at non-zero offset
        char[] slots = {'[', ' ', ' ', ' ', ']'};
        "NET".getChars(0, 3, slots, 1);
        if (new String(slots).equals("[NET]")) {
            System.out.println("Check 2 Passed: Characters inserted at destination offset 1.");
        }

         // 3. Verify zero-length slice performs no-op
        source.getChars(3, 3, buffer, 0);
        System.out.println("Check 3 Passed: Zero-length range executed safely.");

        System.out.println("All String.getChars() unit checks passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: Exact string slice copied into array.
Check 2 Passed: Characters inserted at destination offset 1.
Check 3 Passed: Zero-length range executed safely.
All String.getChars() unit checks passed successfully!

10. Frequently Asked Questions (FAQ) 🔝

Does getChars() create a byte array or a char array?

getChars() strictly copies into a char[] (16-bit characters). For binary byte arrays, use getBytes().

Why does getChars() return void?

Because it writes directly into the pre-allocated destination array passed as an argument, eliminating unnecessary return object allocations.

What happens if srcBegin equals srcEnd?

Zero characters are copied. The method completes successfully as a safe no-op without altering the destination array.

How do I convert a char[] back to a String?

Use String.copyValueOf(chars) or String.valueOf(chars).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer