How to Convert Char to Int in Java

  1. Use Character.getNumericValue(ch) to Convert a char to an int
  2. Subtract the Given char From 0 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

  • How to Check if a String Is an Integer in Java
  • How to Get the Separate Digits of an Int Number in Java
  • Related Article - Java Char

  • How to Check if a String Is an Integer in Java
  • How to Convert a Char to a String in Java
  • comments powered by Disqus