I was curious about how exactly the overflow (leading to an answer of -83118960) was behaving so I looked into what was happening.
Let’s first break up the expression into 3 parts to better understand the behaviour as Java evaluates it:
t = 1920*1080*2000/1920*1080
is equivalent to
t = 1920*1080*2000 // a
t/= 1920 // b
t*= 1080 // c
a) Overflow
1920*1080*2000
evaluates to 4147200000, which is greater than Java’s 32 bit signed integer limit (2147483647) so an overflow happens, which behaves as follows:
First know that 2147483647 + 1 evaluates (wraps around) to -2147483648, because the sign bit gets flipped from 0 to 1 and all other digits roll over to zero (10000000 00000000 00000000 00000000
). And now, as the bits count up, the number becomes less negative (Two’s complement).
The point above can be generalised to 2147483647 + N = -2147483648 + (N-1)
Coming back to our number, its “raw overflow”, N, is 4147200000-2147483647 = 1999716353.
So, at this stage the temporary result is -2147483648 + (1999716353-1) = -147767296 (note this is the same as 4147200000-(2^31)*2
).
b) Integer Division
Now Java computes the result from before (-147767296) divided by 1920.
Working with floats, this would equal -76962.1333. However, as both numbers are integers, Java performs integer division, so the result is automatically rounded towards 0.
So, at this stage the temporary result is -76962.
c) Multiplication
Finally, -76962 is multiplied by 1080.
The result? -83118960, a.k.a. -8.311896E7.