Java – Convert string to char array
To convert a string to char array in Java, you can use String.toCharArray() method. Call the toCharArray() method on the given string, and the method returns a char array created from the characters of the string.
In this tutorial, we will learn how to use a convert a given string to an array of characters in Java, with examples.
1. Convert string “HelloWorld” to char array in Java
In this program, we shall take a string "Hello World"
in variable str, convert this string to a char array characters, and then print them to output using a For loop.
Java Program
</>
Copy
public class Main {
public static void main(String[] args) {
String str = "HelloWorld";
// Convert string to char array
char[] characters = str.toCharArray();
// Print the array
for(var i=0; i<characters.length; i++) {
System.out.println("characters["+ i +"] - " + characters[i]);
}
}
}
Output
characters[0] - H
characters[1] - e
characters[2] - l
characters[3] - l
characters[4] - o
characters[5] - W
characters[6] - o
characters[7] - r
characters[8] - l
characters[9] - d
Conclusion
In this Java String tutorial, we have seen how to convert a given string into an array of characters using String.toCharArray() method, with examples.