why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE?

Oleg Mikheev picture Oleg Mikheev · Feb 22, 2012 · Viewed 39.1k times · Source

System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);

is true.

I understand that integer in Java is 32 bit and can't go above 231-1, but I can't understand why adding 1 to its MAX_VALUE results in MIN_VALUE and not in some kind of exception. Not mentioning something like transparent conversion to a bigger type, like Ruby does.

Is this behavior specified somewhere? Can I rely on it?

Answer

Bozho picture Bozho · Feb 22, 2012

Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE. Relevant JLS

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.