Can someone please explain why this following statement:
short value = (short) 100000000;
System.out.println(value);
Gives me:
Here's good article explaining narrowing and widening primitive conversions in Java.
short s = 696; // 0000 0010 1011 1000 byte x = (byte)s; System.out.println("byte x = " + x);
Produces:
byte x = -72
Now you should understand why - because when we narrow short down to the byte the JVM discards the most significant part (00000010) and the result (in binary form) is 10111000. This is the same number we were looking at before. And, as you can see, it is negative, unlike the original value.
The way you did it merely reinterprets a smaller number of bits at the same memory location. It does not change them.
You probably want to use the max
and min
functions to detect when the value lies beyond of short
and assign the max or min value of the short when that happens.
int n = 1000000;
short value = n > Short.MAX_VALUE ? Short.MAX_VALUE : n < Short.MIN_VALUE ? Short.MIN_VALUE : (short)n;
Update: more compactly:
import static java.lang.Math.max;
import static java.lang.Math.min;
// ...
value = (short)min(max(value, Short.MIN_VALUE), Short.MAX_VALUE);
System.out.println(value);
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.