Why does incrementing a Java int eventually result in a negative number?

Why does it goes to negative?

Because that is what is specified to happen in Java when an int calculation overflows.

JLS 15.18.2

“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.”


(This doesn’t explicitly say that overflow always gives a negative number. And it doesn’t always. But if you apply the rule, it does explain why incrementing Integer.MAX_VALUE by +1 gives you Integer.MIN_VALUE …)

Leave a Comment