Java How To Convert a String to an Array
Convert a String to an Array
There are many ways to convert a string to an array. The simplest way is to use the toCharArray()
method:
Example
Convert a string to a char
array:
// Create a string
String myStr = "Hello";
// Convert the string to a char array
char[] myArray = myStr.toCharArray();
// Print the first element of the array
System.out.println(myArray[0]);
Try it Yourself »
You can also loop through the array to print all array elements:
Example
// Create a string
String myStr = "Hello";
// Convert the string to a char array
char[] myArray = myStr.toCharArray();
// Print array elements
for (char i : myArray) {
System.out.println(i);
}
Try it Yourself »
Related Pages
The toCharArray() String Method