Java String.toCharArray
Create a new, editable array containing the string’s UTF-16 units.
A simple example
String.toCharArray
- Start with "AB"
- Do this Make a character array
- Result A, B
class Main {
public static void main(String[] args) throws Exception {
System.out.println(java.util.Arrays.toString("AB".toCharArray()));
}
}
[A, B]
Syntax
public char[] toCharArray()
JDK 21 method signatures (1)
public char[] toCharArray()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaMask one position in a badge preview
A check-in screen should hide one position in a badge number. Update the preview field at its intended position and keep the full identifier available for internal lookup.
class Main {
public static void main(String[] args) throws Exception {
String badge = "A712";
char[] preview = badge.toCharArray();
preview[1] = '*';
System.out.println(new String(preview));
}
}
A*12
Editing the copied array changes only the preview.
Read the original after editing a copy
A preview changes one position in a badge or label while a master copy is still needed. Work out which value is mutable so editing the preview cannot alter the source used for the next print.
class Main {
public static void main(String[] args) throws Exception {
String code = "LAB";
char[] copy = code.toCharArray();
copy[0] = 'X';
System.out.println(code);
}
}
LAB
The original immutable String retains its L.
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 array is a copy. For whole Unicode code points, use codePoints instead.