Originally posted by Isabel Wanderley:
Hi...
I was doing a mock test and I didn't understood how it works:
short i = (short)Float.NEGATIVE_INFINITY;
short j = (short)Float.POSITIVE_INFINITY;
short k = (short)Float.NaN;
when run this the values are: i=0, j=-1 and k=0.
Can anyone explain it to me ? Thanks!
When a floating point number is converted to a type T, it is first converted to an int if T is a byte, short, char, or int. If the float value is more negative than Integer.MIN_VALUE, then the float value is converted to Integer.MIN_VALUE. When Integer.MIN_VALUE is subsequently converted to type short it becomes zero.
The hexadecimal representation of Integer.MIN_VALUE is 0x80000000. When 0x80000000 is converted to a short it becomes zero becuase only the low order 16 bits are used.
A similar process is used to convert Float.POSITIVE_INFINITY to a short. First Float.POSITIVE_INFINITY is converted to Integer.MAX_VALUE which is 0x7FFFFFFF. When 0x7FFFFFFF is converted to a short it becomes 0xFFFF which is the two's compliment representation of -1.
When Float.NaN is converted to an integral value it always becomes zero.