How can a integer and a character be in same mathematical expression?

character, integer, java

Solution

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

- ...

Problem

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?

Original source