How to Convert Char to Int in Java

Hassan Saeed Feb 02, 2024
  1. Use Character.getNumericValue(ch) to Convert a char to an int
  2. Subtract the Given char From 0 in Java
How to Convert Char to Int in Java

This tutorial discusses methods to convert a char to an int in Java.

Use Character.getNumericValue(ch) to Convert a char to an int

The simplest way to convert a char to an int in Java is to use the built-in function of the Character class - Character.getNumericValue(ch). The below example illustrates this:

public class MyClass {
  public static void main(String args[]) {
    char myChar = '5';
    int myInt = Character.getNumericValue(myChar);
    System.out.println("Value after conversion to int: " + myInt);
  }
}

Output:

Value after conversion to int: 5

Subtract the Given char From 0 in Java

Another way to convert a char to an int is to subtract it from the char 0. The below example illustrates this:

public class MyClass {
  public static void main(String args[]) {
    char myChar = '5';
    int myInt = myChar - '0';
    System.out.println("Value after conversion to int: " + myInt);
  }
}

Output:

Value after conversion to int: 5

These are the two commonly used methods to convert a char to an int in Java. However, keep in mind that even if the given char does not represent a valid digit, the above methods will not give any error. Consider the example below.

public class MyClass {
  public static void main(String args[]) {
    char myChar = 'A';
    int myInt = myChar - '0';
    System.out.println("Value after conversion to int: " + myInt);
  }
}

Output:

Value after conversion to int: 17

Even though the input char was an alphabet, the code ran successfully. Therefore, we must ensure that the input char represents a valid digit.

Related Article - Java Int

Related Article - Java Char