What???
The expected sum of 3 billion (1 billion + 2 billion)
does not correctly fit into an int
.
There are not enough bits in a 32-bit int
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.
There will be some sort of pattern in the int
.
Just not the correct one.
Here is another program fragment and its (surprising) 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
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.
Half of the bit patterns are used for positive integers the other half for negative.
When a sum of positives is too large the resulting bit pattern frequently is
one that represents a negative.
What is the output of the following? Pay attention to the L
at
the end of the numbers.
if ( 1_000_000_000L + 2_000_000_000L > 0 ) System.out.println("Obviously True"); else System.out.println("What???");