Edit: live demo
Here's what's going on when you add those numbers:
int a = 2147483647;
int b = 2147483647;
In binary:
a = 0b01111111111111111111111111111111
b = 0b01111111111111111111111111111111
Adding those numbers together gives a number larger than Integer.MAX_VALUE
(obviously):
long c = a + b; // -2
In binary:
0b01111111111111111111111111111111
+ 0b01111111111111111111111111111111
------------------------------------
0b11111111111111111111111111111110
== -2 when taking into account 2's complement
The result is then upcast to a long
.
To ensure the numbers are added as long
s and not int
s, make a
and b
both long
s.