How to convert Java String to char
In Java, a String can be converted into a char by using built-in methods of String class and own custom code. The following are the methods that will be used in this topic to convert string to char.
-
charAt() method
-
toCharArray() method
1. By Using charAt()
Method
The charAt() method is a part of String class. This method is used to return the single character of the specified index. It must be noted that this method returns only a single character and in order to get multiple characters, looping should be used.
Example 1:
By using the charAt() method , the character at a specified index is returned from the given string charAt(0)
returns the first character of the String.
public class StudyTonight
{
public static void main(String args[])
{
String s = "studytonight";
char c = s.charAt(0);//returns s
System.out.println("1st character is: " +c);
}
}
1st character is: s
Example 2:
Here, the entire string is converted into character using the loop.
public class StudyTonight
{
public static void main(String args[])
{
String s = "mohit";
for(int i=0; i<s.length();i++)
{
char c = s.charAt(i);
System.out.println("char at "+i+"th index is: "+c);
}
}
}
char at 0th index is: m
char at 1th index is: o
char at 2th index is: h
char at 3th index is: i
char at 4th index is: t
2. By using the toCharArray()
Method
The toCharArray() method is a part of String class. This method converts the String into a character array.
Example 3:
Here, the String is converted into a character array by using the toCharArray()
method. See the example below.
public class StudyTonight
{
public static void main(String args[])
{
String s = "mohit";
for(int i=0; i<s.length();i++)
{
char[] c = s.toCharArray();
System.out.println("char at "+i+"th index is: "+c[i]);
}
}
}
char at 0th index is: m
char at 1th index is: o
char at 2th index is: h
char at 3th index is: i
char at 4th index is: t