Java Program to Convert Char to Int

In this java program, we will learn about how to convert a character(char) data type variable to an integer(int) data type variable. There are several methods in Java for converting from Char to Int. The ASCII value of a particular character will be returned if we directly assign a char variable to an int.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Convert Char to Integer using getNumericValue() method

By calling the Character.getNumericValue(char) method on a char variable that contains an int value, we can retrieve the int value.

public class CharToInteger1 {
  public static void main(String[] args) {
    char ch = '2';

    int num = Character.getNumericValue(ch);
    System.out.println(num);
  }
}
Output
2

In this java program, character '2' is converted into an integer value 2.


Java Program to Convert Chanr to Integer using parseInt() method

The valueOf() method of String class can convert various types of values to a String value. It can convert int, char, long, boolean, float, double and char array to String, which can be converted to an int value by using the Integer.parseInt() method.

public class CharToInteger2 {
  public static void main(String[] args) {
    char ch = '4';

    int num = Integer.parseInt(String.valueOf(ch));
    System.out.println(num);
  }
}
Output
4

Java Program to Convert Char to Integer using ASCII Value

In Java, we can also convert the character into an integer by subtracting it with character '0'. In other words, this method converts the char to int by finding the difference between the ASCII value of this char and the ASCII value of '0'.

public class CharToInteger3 {
  public static void main(String[] args) {
    char ch = '5';

    int num = ch - '0';
    System.out.println(num);
  }
}
Output
5