Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is System.out.println(4*2147483647) equal to -4 in java?

Tags:

java

I am a Java beginner and pretty confused with this.

How is System.out.println(4*2147483647) equal to -4 in java?

like image 832
shawn Avatar asked Aug 03 '12 12:08

shawn


Video Answer


2 Answers

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.

like image 94
assylias Avatar answered Nov 11 '22 09:11

assylias


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.

like image 38
Augusto Avatar answered Nov 11 '22 09:11

Augusto