Conversions
Java Program to Convert String to Char
A Java program to convert a String to a Char.
Problem Description
Write a Java program to convert a String to a Char.
Code
public class StringToChar {
public static void main(String[] args) {
String s = "hello";
// Method 1: charAt()
char c = s.charAt(0);
System.out.println("1st character is: " + c);
// Method 2: toCharArray()
char[] ch = s.toCharArray();
for(int i = 0; i < ch.length; i++){
System.out.println("char at " + i + " index is: " + ch[i]);
}
}
}Output
1st character is: h
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: oExplanation
charAt(): Returns the char value at the specified index.toCharArray(): Converts this string to a new character array.
