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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.