Can someone please explain why this following statement:
short value = (short) 100000000;
System.out.println(value);
Gives me:
-7936
Knowing that the maximum value of a short in Java is 32767 correct?
With your value of 100 million, I get -7936. I can only get 16960 if I change 100 million to 1 million.
The reason is that short
values are limited to -32768 to +32767, and Java only keeps the least significant 16 bits when casting to a short
(a narrowing primitive conversion, JLS 5.1.3). Effectively this operation: 1 million mod 2^16 (16 bits in a short
) is 16960.