How can I convert a char to int in Java?

Haim Lvov picture Haim Lvov · Sep 21, 2017 · Viewed 184.4k times · Source

(I'm new at Java programming)

I have for example:

char x = '9';

and I need to get the number in the apostrophes, the digit 9 itself. I tried to do the following,

char x = 9;
int y = (int)(x);

but it didn't work.

So what should I do to get the digit in the apostrophes?

Answer

khelwood picture khelwood · Sep 21, 2017

The ASCII table is arranged so that the value of the character '9' is nine greater than the value of '0'; the value of the character '8' is eight greater than the value of '0'; and so on.

So you can get the int value of a decimal digit char by subtracting '0'.

char x = '9';
int y = x - '0'; // gives the int value 9