Sobes.tech
Middle

Why is Integer.MAX_VALUE plus one equal to Integer.MIN_VALUE?

sobes.tech AI

Answer from AI

Integer.MAX_VALUE is the maximum value for a 32-bit signed integer type in Java. It equals 2<sup>31</sup> - 1.

Memory representation:

Integer.MAX_VALUE: 0111...1111 (31 ones)

Adding one causes overflow:

Integer.MAX_VALUE + 1:

  0111...1111
+ 0000...0001
------------
  1000...0000

The most significant bit becomes one, which in signed representation indicates a negative number. For two's complement (the standard representation of negative numbers in Java), 1000...0000 corresponds to the smallest negative number that can be represented with 32 bits, which is Integer.MIN_VALUE (-2<sup>31</sup>).

This behavior is standard for signed integer types when overflow occurs in Java and many other languages that use two's complement.