Java String.getChars
Copy a range of UTF-16 units into a caller-provided character array.
A simple example
String.getChars
- Start with Characters a, b, c
- Do this Copy just the middle character
- Result b
Syntax
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
JDK 21 method signatures (1)
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCopy a parcel number into a print buffer
A scanner returns a compound code, but the printed field needs only its numeric or trailing portion. Use the input boundaries and destination capacity to copy the intended range without including the prefix.
class Main {
public static void main(String[] args) throws Exception {
String parcel = "PK-482";
char[] digits = new char[3];
parcel.getChars(3, 6, digits, 0);
System.out.println(new String(digits));
}
}
482
Only the three numeric positions are copied.
Fill a badge template in place
A printer has a template with room reserved for a short code. Copy the text into the intended positions so the surrounding brackets or other fixed characters stay in place.
class Main {
public static void main(String[] args) throws Exception {
char[] badge = "[ ]".toCharArray();
"LAB".getChars(0, 3, badge, 1);
System.out.println(new String(badge));
}
}
[LAB]
Destination offset one preserves both brackets.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Copy the last two characters into a clean buffer for a numeric display. What does the copied field contain?
What to watch for
The end offset is exclusive and the destination must have room for the entire range.