Java Primitives range calculation [duplicate]
Solution 1:
The compiler will, in this case, evaluate the calculation (because it contains only constants) and try to assign the result to the variable. This calculation is done with type int
and only converted to short
on assignment, if at all possible.
In your case, the first calculation is too large to fit into a short
(1073741824
). The second one will overflow the int
and end up in a range that short
supports (0
). So the assignment works in that case.
Mind you, you probably don't ever want to rely on these things in code.
Solution 2:
You are facing the problem as your number is wrapping around.In the first case it does not wrap around and hence it overflows the range of short. But in the second case it wraps around after the calculationa and hence it comes in the range of short and so you dont have the compile time error.
A loss of precision means that you are losing information of the given value.(The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).) In your first case the range of short is crossed(1073741824) and hence you are loosing the information.
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.
EDIT:-
From JLS §3.10.1(very correctly mentioned in this similar question)
It is a compile-time error if a decimal literal of type int is larger than 2147483648 (231), or if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator (§15.15.4).