Java Program to convert char type variables to int

Example 1: Convert char to int

class CharToInt {
  public static void main(String[] args) {

    // create char variables
    char a = '5';
    char b = 'c';

    // ASCII value of characters are assigned
    int num1 = a;
    int num2 = b;

    System.out.println(num1);    
    System.out.println(num2);   
  }
}
Output
53
99

In the above example, we are assigning char type variable to int. Internally, java converts the char variable to its corresponding ASCII values. Here ASCII value of char 5 is 53 and char c is 99.

Example 2: Convert char to int using getNumericValue() method

There is another method in Character class getNumericValur() which takes the numberic value of character and stores it in num1 and

class CharToInt {
  public static void main(String[] args) {

    // create char variables
    char a = '5';
    char b = '9';

    // Use getNumericValue()
    int number1 = Character.getNumericValue(a);
    int number2 = Character.getNumericValue(b);

    // print the numeric value of characters
    System.out.println(number1);    
    System.out.println(number2);  
  }
}
Output
5
9

Example 3: Converting char to int using parseInt() method

Here

class CharToInt {
  public static void main(String[] args) {

    // create char variables
    char a = '5';
    char b = '9';

    // Use parseInt()
    int number1 = Integer.parseInt(String.valueOf(a));
    int number2 = Integer.parseInt(String.valueOf(b));

    // print numeric value of character
    System.out.println(number1);   
    System.out.println(number2);    
  }
}
Output
5
9

Here, String.valueOf(a) convers the character variable into String and Integer.parseInt() converts the String variable into int.

Example 4: Finally, char to int by subtracting with ‘0’

class CharToInt{
  public static void main(String[] args) {

    // create char variables
    char a = '9';
    char b = '3';

    // convert char variables to int by subtracting with char 0
    int num1 = a - '0';
    int num2 = b - '0';

    // print numeric value of character
    System.out.println(num1);   
    System.out.println(num2);   
  }
}
Output
9
3

Leave a Reply