I am a Java beginner and pretty confused with this.
How is System.out.println(4*2147483647)
equal to -4 in java?
It is due to integer silent overflow.
2147483647 == Integer.MAX_VALUE
is the maximum value for an integer.
Silent overflow means that 2147483647 + 1 == Integer.MIN_VALUE = -2147483648
You can then see that 2147483647 + 2147483647 == 2147483647 + (-2147483648 + - 1) == -2
In other words, 2147483647 * 2 == -2
, and you can now see why 2147483647 * 4 == -4
.
More technically, the result is defined by the Java Language Specification #15.17.1:
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.
It has to do with the way processors perform a binary mutiplication. The number you have in there is the maximum signed integer, which is represented as 0111111111111111111111111 (I haven't checked the number of ones there, but I assume you get the idea).
When you mutiply by 4, is like doing a left shift by 2, which results in 11111111111111111111100 (which represents -4). You might want to read how mutiplication is done in binary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With