String to char Conversion in Java

String to char Conversion: Sometimes, we obtain the values in string fomrat in Java. Printing the value is no problem (as long as user gets the same output) as it prints the same value as data type prints.

For example, a char value is obtained in string format as in command-line arguments or from TextField's getText() method. The string value is to be converted into char format to use in coding as strings cannot be used as chars; both are very different. To get the char from the string, the String class method charAt() can be used. This is the easiest way; the other ways are using substring() of String class and charValue() of Character class etc.

Example on String to char conversion
public class Conversions
  public static void main(String args[])
    String str = "A";
    System.out.println("A in String form: " + str);           // printing is no problem

    char ch = str.charAt(0);                   // String to char conversion, no parsing

    System.out.println("A in char form: " + ch);         

String to char
Output screenshot on String to char Example

char ch = str.charAt(0);

charAt(int) is a method of String class which returns the character at the index 0 in the string str.

Using parsing operations, it is possible to convert string to other data types byte, short, int, long, float, double and boolean also.

Note: The other way char to string is also possible.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.