1024 * 1024 * 1024 * 1024
and 2147483648
do not have the same value in Java.
Actually, 2147483648
ISN'T EVEN A VALUE(although 2147483648L
is) in Java. The compiler literally does not know what it is, or how to use it. So it whines.
1024
is a valid int in Java, and a valid int
multiplied by another valid int
, is always a valid int
. Even if it's not the same value that you would intuitively expect because the calculation will overflow.
Example
Consider the following code sample:
public static void main(String[] args) {
int a = 1024;
int b = a * a * a * a;
}
Would you expect this to generate a compile error? It becomes a little more slippery now.
What if we put a loop with 3 iterations and multiplied in the loop?
The compiler is allowed to optimize, but it can't change the behaviour of the program while it's doing so.
Some info on how this case is actually handled:
In Java and many other languages, integers will consist of a fixed number of bits. Calculations that don't fit in the given number of bits will overflow; the calculation is basically performed modulus 2^32 in Java, after which the value is converted back into a signed integer.
Other languages or API's use a dynamic number of bits (BigInteger
in Java), raise an exception or set the value to a magic value such as not-a-number.