Java: Converting a char to an int

Digits: Converting character '5' to integer 5:

char c = '5';
int i = c - '0';  // i == 5

ASCII: Converting 'A' to 65:

char c = 'A';
int i = c;        // i == 65

Ehm, what?!

In Java a char has a dual interpretation in the form of it's numerical ASCII value (or code point to be precise). We here use the fact that '0', … '9' have sequential ASCII values ('0' has value 48, '1' has value 49, and so on). This means that 'n' - '0' = n.

Comments (3)

User avatar

Also a standard Character.digit method could be used. E.g. Character.digit('9', 10) == 9 (int).

by georgeek |  Reply
User avatar

What happens if you add a number, say 5 to C or any other character?

by Anonymous |  Reply
User avatar

If you add 5 to C you'll get an H (or 72 if you look at it as an int). You can try running this yourself: System.out.println('C' + 5);.

by Anonymous |  Reply

Add comment