LAST UPDATED: DECEMBER 1, 2020
How to convert Java char to int
In Java, a char value can be converted into int using by the following ways
1. Getting ASCII Value
When a char value is directly assigned as an int it returns the integer ASCII value assigned to the char value.
Example 1:
Here, the ASCII value associated with the char variable is returned.
public class StudyTonight
{
public static void main(String args[])
{
char c1 = 'm';
char c2 = 'M';
int n1 = c1;
int n2 = c2;
System.out.println("The equivalent ASCII value is " +n1);
System.out.println("The equivalent ASCII value is " +n2);
}
}
The equivalent ASCII value is 109
The equivalent ASCII value is 77
2. Character.getNumericValue()
Method
The getNumericValue()
method is a part of Character class that returns the numeric(int) value of the character holds.
Example 2:
Here, a int value assigned to the character is returned using the Character.getNumericValue() method.
public class StudyTonight
{
public static void main(String args[])
{
char ch = '8';
int n = Character.getNumericValue(ch);
System.out.println("The int value is : " +n);
}
}
The int value is : 8
3. Integer.parseInt()
method
The parseInt()
method is a part of the Integer
class and returns an int value of the specified object value.
Example 3:
Here, the char value is converted to string first then converted to integer by using parseInt()
method. the integer value is returned to the specified character value.
public class StudyTonight
{
public static void main(String args[])
{
char ch = '5';
int n = Integer.parseInt(String.valueOf(ch));
System.out.println("The integer value is " +n);
}
}
The integer value is 5