Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a char to int in Java? [duplicate]

(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?

like image 941
Haim Lvov Avatar asked Sep 21 '17 12:09

Haim Lvov


People also ask

How do I convert a char to an int in java?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.

How do I turn a char into an int?

valueOf(a) - converts the char type variable a into a String. Integer. parseInt() - converts the string into an int.

Can you multiply a char by an int in java?

char can be multiplied by integer in java.

Can double be converted to int java?

round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.


1 Answers

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 
like image 158
khelwood Avatar answered Oct 10 '22 22:10

khelwood