Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 530
Zohaib Amir Avatar asked Dec 26 '22 14:12

Zohaib Amir


1 Answers

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
  • ...
like image 71
Xavi López Avatar answered Mar 23 '23 00:03

Xavi López