Java Integers Min_Value negative then compare

Quinma picture Quinma · Sep 21, 2012 · Viewed 19.2k times · Source

I have a test tomorrow and I cant understand my books explanation, I appreciate the help:

public class TestClass{
      public static void main(String[] args) throws Exception{
            int a = Integer.MIN_VALUE;
            int b = -a;
            System.out.println( a+ "   "+b);
      }
}

Output: -2147483648 -2147483648

Why does this print 2 negative numbers of the same magnitude and not a positive and negative?

Answer

assylias picture assylias · Sep 21, 2012

Because of silent integer overflow: Integer.MIN_VALUE is -2^31 and Integer.MAX_VALUE is 2^31-1, so -Integer.MIN_VALUE is 2^31, which is Integer.MAX_VALUE + 1, which by definition is too large for an integer. So it overflows and becomes Integer.MIN_VALUE...

You can also check that:

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

prints the same thing.

More technically, the result is defined by the Java Language Specification #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.