Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

Java String.toCharArray() method

Reference for Java String.toCharArray(): copy a string into a char array to sort, modify or count characters, then turn it back into a String.

toCharArray() returns a new char[] containing the characters of the string. Because strings are immutable, the array is the way to edit text in place: change elements, sort them, swap them, and then build a new string from the result with new String(chars) or String.valueOf(chars).

The array is a copy. Changing it never affects the original string, and the original can never be changed through it.

Java
char[] letters = "dcba".toCharArray();
Arrays.sort(letters);
String sorted = new String(letters); // "abcd"

Try it

Java Sort, reverse and rebuild

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Anagrams and letter counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public char[] toCharArray()

Returns: a newly allocated array whose length is the string's length() and whose contents are its UTF-16 code units.

Throws: nothing.

Usage notes

  • It always copies, so each call costs O(n) time and memory. Call it once and keep the array if you need it repeatedly.
  • UTF-16 code units, not characters. Characters outside the Basic Multilingual Plane (most emoji) become two char elements. Use codePoints() when that matters.
  • Rebuilding: new String(chars), String.valueOf(chars) and new String(chars, offset, count) all copy again; the array can be reused afterward.
  • Iteration without a copy: for (int i = 0; i < s.length(); i++) s.charAt(i) avoids the array and is often just as readable. for (char c : s.toCharArray()) is the concise form.
  • Passwords: an array can be overwritten with Arrays.fill(chars, '\0'), which is why APIs such as Console.readPassword() return char[]. Converting a secret to a String leaves an immutable copy you cannot clear.
  • Sorting characters with Arrays.sort() orders by numeric char value, so uppercase letters come before lowercase ones.
  • Not a stream. For a functional pipeline use chars().