How do I convert from a char to an int?


If you want to get the ASCII value of a character, or just convert it into an int (say for writing to an OutputStream), you need to cast from a char to an int.

What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.

public class char_to_int
      public static void main(String args[])
           char myChar = 'a';
           int  i = (int) myChar; // cast from a char to an int

           System.out.println ("ASCII value - " + i);

In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.

Related questions

How do I convert from an int to a char?