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:
The conversion from char
(a 2-byte type) to int
(a 4-byte type) is implicit in Java, because this is a widening conversion -- all of the possible values you can store in a char
you can also store in an int
. The reverse conversion is not implicit because it is a narrowing conversion -- it can lose information (the upper two bytes of the int
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.