A more interesting casting option is converting a
char to a number type, or the other way around. Just like before, you have to be careful how you set this up. In the back-end, a
char doesn’t store
'a', it stores the value representing that: 97 for lowercase and 65 for uppercase.
int targetInt; char sourceChar = 'a'; targetInt = (int)sourceChar;
targetInt equals 97.
When you cast an
int to a
char, you get the opposite process and the
char is set to the value at the
int value. So if you did:
int sourceInt = 65; char targetChar; sourceInt = (char)targetChar;
targetChar now equals
'a' is 97, what do you suppose we would get if we set an
int to 99 and cast it to a
char? Let’s find out. The initial state is set so you need to cast our
targetChar equal to
sourceInt and explicitly cast it by using
Now let’s see what happens when you cast a
double into a
sourceDouble using implicit casting (no type identifier for the cast).