Java char to int

In Java, you can convert a char to an int by simply casting the char to an int. This will give you the Unicode (ASCII) value of the character.

Example:


public class CharToIntExample {
    public static void main(String[] args) {
        char myChar = 'A';
        int myInt = (int) myChar; // Cast char to int
        System.out.println("The integer value of '" + myChar + "' is: " + myInt);
    }
}

Output: The integer value of ‘A’ is: 65

Explanation:

  • The char data type in Java represents a single 16-bit Unicode character.
  • When you cast a char to an int, it gives you the Unicode value of that character. For example, ‘A’ has the Unicode value 65.

Using Character.getNumericValue() Method

This method converts a char to an integer that represents the numeric value of the character. This is useful when dealing with numeric characters (like ‘0’ through ‘9’), but it also works with any character.

Example:


public class CharToIntExample {
    public static void main(String[] args) {
        char myChar = '9';
        int myInt = Character.getNumericValue(myChar); // Convert to int
        System.out.println("The integer value of '" + myChar + "' is: " + myInt);
    }
}

Output: The integer value of ‘9’ is: 9

Using String.charAt() Method

If you’re working with a string and want to extract a character and convert it to an int, you can use String.charAt() to get the character at a particular index and then cast it.


public class CharToIntExample {
    public static void main(String[] args) {
        String myString = "Hello";
        int myInt = (int) myString.charAt(0); // Convert the first character to int
        System.out.println("The integer value of '" + myString.charAt(0) + "' is: " + myInt);
    }
}

Output: The integer value of ‘H’ is: 72

Explanation:

  • charAt(0) retrieves the first character of the string.
  • The cast to int will give you the Unicode value of the character, just like with the direct cast method.