It is possible to convert String into char in Java by using the charAt() method of the String class.
This charAt() method gives a single character. To obtain the entire characters, make use of the loop.
Signature
A method charAt() method returns one character from the index that is specified. The method’s signature of the charAt() technique is as follows: below:
public char charAt(int index)
Java String to the char example method: CharAt() method
Let’s look at the easy method to convert String to char using Java using the charAt() procedure.
Let’s look at the easy example of changing String into characters in Java.
String s="hello";
char c=s.charAt(0);//returns h
Let’s look at another way to convert all characters in the string into characters.
public class StringToCharExample1{
public static void main(String args[]){
String s="hello";
char c=s.charAt(0);//returns h
System.out.println("1st character is: "+c);
}}
Output:
1st character is: h
Let’s see another example to convert all characters of a string into characters.
public class StringToCharExample2{
public static void main(String args[]){
String s="hello";
for(int i=0; i<s.length();i++){
char c = s.charAt(i);
System.out.println("char at "+i+" index is: "+c);
}
}}
Output:
char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o
Java String to CharArray Example:() method
Let’s look at the simple code that converts String to char in Java using the toCharArray() technique. It is the toCharArray() method in the String class that transforms this string into a characters array.
public class StringToCharExample3{
public static void main(String args[]){
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.println("char at "+i+" index is: "+ch[i]);
}
}}
Output:
char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o