Google News
logo
Java int to char conversion
Java, we can convert an int value to its corresponding char value using the (char) cast operator.

Here are some examples :
Program :
public class CharToIntExample {
    public static void main(String[] args) {
        char ch1 = 'A'; // character 'A'
        char ch2 = '5'; // character '5'
        int num1 = ch1; // convert char to int
        int num2 = ch2; // convert char to int
        System.out.println(num1); // output: 65
        System.out.println(num2); // output: 53
    }
}
Output :
65
53
In this program, we have defined two char variables ch1 and ch2 with the values 'A' and '5', respectively. We then assign these variables to int variables num1 and num2 using the = operator, which automatically performs the conversion from char to int.

Finally, we print the values of num1 and num2 using the System.out.println() method, which outputs the corresponding ASCII values of characters 'A' and '5', respectively.

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

We can also use the getNumericValue() method of the Character class to convert the char type variable into int type.
Program :
class Main {
  public static void main(String[] args) {

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

    // convert char variables to int
    // Use getNumericValue()
    int num1 = Character.getNumericValue(a);
    int num2 = Character.getNumericValue(b);

    // print the numeric value of characters
    System.out.println(num1);    // 5
    System.out.println(num2);    // 9
  }
}
Output :
59
Here, as we can see the getNumericValue() method returns the numeric value of the character. The character '5' is converted into an integer 5 and the character '9' is converted into an integer 9.