Hi everyone,
While doing a mock exam recently, I was asked to select whether
the statement would compile or not -
char chr = (int)Integer.MAX_VALUE;
I felt it would compile as it was a narrowing conversion, but was proved incorrect. Wrote a small
test program to check this.
If the line is uncommented out, the compiler complains about possible loss of precision. In the case of narrowing conversion for the int variable j,this does not happen and I get the output as- Int j is 2147483647, clearly showing that loss of precision is tolerated in this case. So there is a difference between how it behaves for a conversion to a char vs other narrowing conversions.
I also checked the JLS, but could not find any explanation for a compilation error. It says-
quote..
A narrowing conversion of a character to an integral type T likewise simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the resulting value to be a negative number, even though characters represent 16-bit unsigned integer values.
unquote
Hope someone can help me here.
Thanks a lot!
Sajida