Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integers Min_Value negative then compare

I have a test tomorrow and I can't 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?

like image 348
Quinma Avatar asked Sep 21 '12 17:09

Quinma


3 Answers

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.

like image 81
assylias Avatar answered Nov 12 '22 15:11

assylias


Basically, because Integer.MAX_VALUE is actually only 2147483647, so -Integer.MIN_VALUE, which would be +2147483648, actually overflows the capacity of the internal binary representation of integers. Thus, the result "loops around" back to Integer.MIN_VALUE, or -2147483648.

If you did long b = -((long)a); instead, you would get the expected result.

like image 30
João Mendes Avatar answered Nov 12 '22 15:11

João Mendes


To show this even more clearly:

Integer.MIN_VALUE is -2^31 = -2147483648
Integer.MAX_VALUE is 2^31-1 = 2147483647 
/*notice this is 1 less than the negative value above*/

Integer.MAX_VALUE can not take 2147483648. This is too large number for Integer by exactly 1. This causes the number to go back on the scale from max value back to starting poing which is the min value.

like image 21
user2332921 Avatar answered Nov 12 '22 17:11

user2332921