Appearance
How to convert/parse from String to char in java?
In Java, you can convert a string to a character using the charAt() method of the String class. This method takes an index as an argument and returns the character at that index.
java
String str = "hello";
char ch = str.charAt(0); // ch will be 'h'You can also use the toCharArray() method to convert a string to an array of characters:
java
String str = "hello";
char[] chars = str.toCharArray(); // chars will be ['h', 'e', 'l', 'l', 'o']Note that toCharArray() creates a new array copy rather than referencing the original string buffer.
Note that if you want to convert a single-character string to a character, you can use charAt(0). To prevent StringIndexOutOfBoundsException, ensure the string is not empty and the index is valid:
java
String str = "h";
char ch = str.isEmpty() ? '\0' : str.charAt(0); // ch will be 'h'