System: Windows Vista 32-bit, Java 6.0.2
I have a few questions about converting chars to ints. I run the code below, leaving myInt with a value of 4:
char myChar = '4';
int myInt = myChar - '0';
Now, is this conversion something that Java does automatically? Was the ascii value of '0' subtracted from ascii '4', and then cast to an int behind the scenes? This is confusing for me because when I try to the reverse operation, I have to actually cast the result as a char:
int anotherInt = 5;
char newChar = anotherInt + '0'; //gives error
char newChar = (char)(anotherInt + '0'); //works fine
Is this occuring because Java is automatically casting (anotherInt + '0') to an int, as in the first example? Thank you.
The conversion from
char
(a 2-byte type) toint
(a 4-byte type) is implicit in Java, because this is a widening conversion -- all of the possible values you can store in achar
you can also store in anint
. The reverse conversion is not implicit because it is a narrowing conversion -- it can lose information (the upper two bytes of theint
are discarded). You must always explicitly cast in such scenarios, as a way of telling the compiler "yes, I know this may lose information, but I still want to do it."If C rules are anything to go by, your char can be automatically coerced into an int without a cast in your first example, as the conversion does not involve a loss of information.
However, an explicit cast is required in your second case, where there is potential to lose information since a char is smaller than an int.