Home
Java
String toCharArray Method
Updated May 20, 2023
Dot Net Perls
ToCharArray. Consider a string: it is immutable and cannot be changed. But an array can be changed. With toCharArray we get a char array from a string.
With this method, we change a string into a mutable form. We can modify letters in the array. Then we convert it back into a String.
Example program. Here we begin with a String that contains the letters "abc." Then we call toCharArray on it. We print this array with Arrays.toString.
Then We assign the first element of the array to the value "A" and print the modified array with Arrays.toString.
Detail We convert the char array to a string with "new String." This invokes the String constructor.
import java.util.Arrays; public class Program { public static void main(String[] args) { String letters = "abc"; // Convert String to a char array. char[] array = letters.toCharArray(); System.out.println(Arrays.toString(array)); // Modify the array. array[0] = 'A'; System.out.println(Arrays.toString(array)); // Get the String. String result = new String(array); System.out.println(result); } }
[a, b, c] [A, b, c] Abc
Notes, toCharArray. Some string manipulations are not simple. We cannot just use insert() or replace() for all things. With toCharArray we can change characters.
String replace
Notes, methods. Code that uses toCharArray can be hard to read. For this reason, placing it in a method can be helpful. These methods can receive a String and return a modified one.
A summary. With toCharArray we have a built-in way to get characters from a String. We do not need to get characters in a loop—we can get them all at once from a Java method.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen