To convert String to char in Java we can use the charAt() method of the String class. This method returns the char value at the specified index.
Syntax
public char charAt(int index)
Example
class Test { public static void main(String[] args) { char ch = "java".charAt(1); // returns char 'a' System.out.println("char: " + ch); } }
Output: char: a
We can also convert a String to a char array using the toCharArray() method.
Syntax
public char[] toCharArray()
Example
class Test { public static void main(String[] args) { String str = "hello java"; char[] charArray = str.toCharArray(); for (char ch : charArray) { System.out.print(ch + ", "); } } }
Output: h, e, l, l, o, , j, a, v, a,
This code declares a variable ‘str’ which is assigned a string “hello java”, it then creates a char array named “charArray” by calling the toCharArray() method on the ‘str’ variable. The code then uses a for-each loop to iterate through the “charArray” and print each character with a comma and space after it.
You can find more on how to print the elements of an array in this tutorial Print Array Elements in Java.
That was all about how to convert String to char in Java. Proceed to the next lesson.
Happy coding!