Java toCharArray: Convert String to Array

This Java example uses the toCharArray method to convert a string into a char array. It creates a String from the array.
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.

String: We convert the char array to a string with "new String." This invokes the String constructor.

Java program that uses toCharArray 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); } } Output [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.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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls