Why is integar.min_value and integar.max_value equal to 1 in java?

601    Asked by AnishaDalal in Java , Asked on Oct 13, 2022

If you run the statement:


System .out.println( (Integer.MIN_VALUE)-(Integer .MAX_VALUE ));
In java it returns 1 as the answer. Is this because Java just considers those values as 32bit integers without considering their sign?
Integer.MIN_VALUE = 10000000000000000000000000000000
Integer.MAX_VALUE = 1111111111111111111111111111111
I get why -MIN.VALUE == MIN_VALUE returns true. And how MAX_VALUE+1 causes the Integer overflow and we get the result. But I cannot clearly wrap my head around how subtraction is working.


Answered by Audrey Berry
Java will overflow and underflow integar.min_value and integar.max_value

max_int = 2147483647 (01111111111111111...1)
min_int = -2147483648 (10000000000000000...0) //first bit is -2^31
under flow:
-2147483648 - 1 = 2147483647
so....
 min_int- max_int = -2147483648 - 2147483647
                  = -2147483648 -(1 + 2147483646)
                  = (-2147483648 - 1) - 2147483646
                  = 2147483647 - 2147483646
                  = 1;

Your Answer

Interviews

Parent Categories