I was studying a book and I found this :
int tiles = ch - 'A';
where ch
is a character.
What I dont understand is how did operating between two characters result an integer?
A char
variable is actually stored in memory as a numeric value. That number represents a specific character (a
, b
, é
, ...), according to a specific codification (usually the ASCII Table).
For instance:
Decimal Char
----------------
65 A
66 B
... ...
You can use a char
variable as if it was a numeric variable. It will be automatically cast and will have the numeric value representing the char
. And viceversa, a numeric value can be interpreted as a char
.
// The ASCII code for 65 is A
int result = 100 - 'A';
System.out.println ("100 - A is " + result); // Prints 35
System.out.println("ASCII code for 65: " + (char)65); // Prints A
Here's a Ideone demo of the code above.
Getting into detail, according to the JLS, sections 5.6.2. Binary Numeric Promotion, and 5.1.2. Widening Primitive Conversion :
19 specific conversions on primitive types are called the widening primitive conversions:
- ...
- char to int, long, float, or double
- ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With