Convert char to int in Java with Examples
Given a character in Java, the task is to convert this character into an integer.
Input: ch = '3' Output: 3 Input: ch = '9' Output: 9
There are various ways in which one can convert char to its int value.
- Using ASCII values: This method uses TypeCasting to get the ASCII value of the given character. From this ASCII value, the respective integer is calculated by subtracting it from the ASCII value of 0. In other words, this method converts the char to int by finding the difference of the ASCII value of this char and ASCII value of 0.
Example:
// Java program to convert// char to int using ASCII valueclassGFG {publicstaticvoidmain(String[] args){// Initializing a character(ch)charch ='3';System.out.println("char value: "+ ch);// Converting ch to it's int valueinta = ch -'0';System.out.println("int value: "+ a);}}Output:char value: 3 int value: 3
- Using String.valueOf(): The method valueOf() of class String, can be used to convert various types of values to String value, It can be used to convert int, char, long, boolean, float, double, object and char array to String. which further can be converted to an int value by using Integer.parseInt() method.
Below program illustrates the use of the valueOf() method.
Example:
// Java program to convert// char to int using String.valueOf()classGFG {publicstaticvoidmain(String[] args){// Initializing a character(ch)charch ='3';System.out.println("char value: "+ ch);// Converting the character to it's int valueinta = Integer.parseInt(String.valueOf(ch));System.out.println("int value: "+ a);}}Output:char value: 3 int value: 3
- Using Character.getNumericValue(): The getNumericValue() method of class Character is used to get the integer value of any specific character. For example, the character ‘9’ will return an int having value 9.
Below program illustrates the use of getNumericValue() method.
Example:
// Java program to convert char to int// using Character.getNumericValue()classGFG {publicstaticvoidmain(String[] args){// Initializing a character(ch)charch ='3';System.out.println("char value: "+ ch);// Converting the Character to it's int valueinta = Character.getNumericValue(ch);System.out.println("int value: "+ a);}}Output:char value: 3 int value: 3
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


