toCharArray() Java - Convert a string to an array of characters
toCharArray() in Java
The toCharArray() method converts a string to an array of char elements.
Syntax
1 |
public char[] toCharArray() |
How to Call the Method:
1 |
char[] result = str.toCharArray(); |
Example:
1 2 3 4 5 6 7 8 9 10 11 |
public class Test { public static void main(String args[]){ String str = "ABC"; char[] result = str.toCharArray(); System.out.println("Char array:"); for (int i = 0; i < result.length; i++) System.out.println("Element [" + i + "]: " + result[i]); } } |
If you run this code on your computer, you will see the following in the console:
Commentary:
There is a string "ABC". With the help of the toCharArray() method, we have turned the string into an array of char elements {'A', 'B', 'C'}.
To show how it works, we used the loop and then displayed every char element in the console.
That's it for this article. You can find more articles in our Java Tutorial for Beginners.