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().
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. |
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] = '