What???
The expected sum of 3 billion (1 billion + 2 billion) does not correctly fit into an int
.
The resulting bit pattern looks like a negative integer.
There are not enough bits to represent the correct sum. This situation (as you might remember) is called overflow. The analogy is pouring 3 quarts of water into a 2 quart container.
But, the 32 bits must contain something; they don't vanish because the answer does not fit. Here is another program and its output:
int a = 1_000_000_000 ; int b = 2_000_000_000 ; System.out.println("The sum of " + a + " and " + b + " is " + (a+b) ); - - - - - - - - - - - - -- - - - - - - - - - - - - The sum of 1000000000 and 2000000000 is -1294967296
Recall that Java gives you no warning when overflow happens.
No Exception
is thrown.
(Some programming languages do throw exceptions when overflow is detected.
But this costs extra machine cycles for every arithmetic operation.
Java opted for speed.)
Details:
The 32 bits of an int
represent both positive integers and negative integers.
So only half of the bit patterns are used for positive integers.
For positive int
s (and zero) the left-most bit (the high-order bit) is zero.
For negative int
s the left-most bit is one.
When a sum of positives is too large the left-most bit sometimes ends up as one,
which makes the result look like a negative.
1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ← negative int 0 0000000000000000000000000000000 ← zero 0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ← positive int x = 0 or 1
Warning: changing the sign of a positive int
is NOT a simple matter of changing the high-order bit from zero to one.
Java int
s are represented with a scheme called two's complement, which is somewhat more complicated than this.
See the notes for assembly language if you want to see how this works.
What is the output of the following?
if ( 1000000000L + 2000000000L > 0 ) System.out.println("Obviously True"); else System.out.println("What???");