Integers that you store with the int
data type are only allocated a limited amount of space in your computer's memory. It's not possible to store every possible integer in this amount of space. So your computer will deal correctly with integers between -2147483648 and 2147483647, because those are enough for most purposes. If you want to store numbers that are outside this range, you need to use a different data type from int
. For example, there's long
(which has a much bigger range) and BigInteger
(which is really limited only by the amount of space allocated to Java itself).
When you add 1 to the largest possible int
, the "correct" answer can't fit in an int
variable. This is a bit like having an abacus with only one line of beads (which can represent numbers from 0 to 9), and trying to work out 9 + 1. Your computer will roll the number over to the smallest possible int
instead. So when you work with int
values, the effect is that 2147483647 + 1 = -2147483648, even though mathematically this makes no sense.