long m = 24 * 60 * 60 * 1000 * 1000;
The above code creates overflow and doesn’t print the correct result.
long m2 = 24L * 60 * 60 * 1000 * 1000; long m3 = 24 * 60 * 60 * 1000 * 1000L;
The above 2 lines print the correct result.
My questions are-
- Does it matter to the compiler which I use,
m2
orm3
? - How does java starts multiplying? Left to right or right to left? Does 24*60 gets computed first or 1000*1000?
Advertisement
Answer
I would use the m2
line instead of the m3
line.
Java evaluates the multiplication operator *
from left to right, so 24 * 60
is evaluated first.
It just so happens that 24 * 60 * 60 * 1000
(one 1000
) doesn’t overflow, so that by the time you multiply by 1000L
(the second 1000
), the product is promoted to long
before multiplying, so that overflow doesn’t take place.
But as you mentioned in your comments, more factors can cause overflow in the int
data type before multiplying the last long
number, yielding an incorrect answer. It’s better to use a long
literal for the first (left-most) number as in m2
to avoid overflow from the start. Alternatively, you can cast the first literal as a long
, e.g. (long) 24 * 60 * ...
.