I am a Java beginner and pretty confused with this.
How is System.out.println(4*2147483647)
equal to -4 in java?
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.
Because the result is out of the range of an int
.
Primitive Data Types
To solve this, use a long
instead of an int
.
The problem is that you are using int (4 bytes) and not long (8 bytes)
System.out.println(4*2147483647);
Try adding an l (for lema) after one of the numbers so that the result is a long and not an Integer. Integer has a max value smaller than your result http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#MAX_VALUE
System.out.println(4l * 2147483647);
or
System.out.println(4 * 2147483647l);
The above two give the correct result. That is 8589934588
Most integers in computer system based on 32-bit which means 4 byte (you can use 64bit or much too). You can have maximum 4,294,967,295 in a 32bit integer. So 4,294,967,295 + 5 will cause overflow give you 5. Also -1 means 4,294,967,295 in integer. Because there is a negative bit.
It's because of how a computer stores numbers in memory. 2147483647 * 4 = 8589934588
8589934588 in binary results in 1 1111 1111 1111 1111 1111 1111 1111 1100
The first one is a bit which signifies the number it preceeds is negative.
The next part can be explained with two's complement.
Two's complement is a way to represent negative values which in calculated by invering all bits, then adding one. This will result in 0011 (the inversion of the last 4 bytes) then adding one causes it to be 0100 which is the binary representation of 4.
Because the sign bit is on negative, it results in -4