Library contents

Java String.toCharArray

Create a new, editable array containing the string’s UTF-16 units.

A simple example

String.toCharArray

  1. Start with "AB"
  2. Do this Make a character array
  3. Result A, B
The two ASCII letters become two separate array elements.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(java.util.Arrays.toString("AB".toCharArray()));
    }
}
Output
[A, B]

Syntax

Java 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.java

Mask 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.

From the programString badge = "A712"
ResultA*12
Main.java
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));
    }
}
Output
A*12

Editing the copied array changes only the preview.

Advertisements

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.

From the programString code = "LAB"
ResultLAB
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String code = "LAB";
        char[] copy = code.toCharArray();
        copy[0] = 'X';
        System.out.println(code);
    }
}
Output
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?

GivenNC-17
Worked result17

What to watch for

The array is a copy. For whole Unicode code points, use codePoints instead.

Documentation for String.toCharArray