-2

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 that 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.

1

2 Answers 2

12

Java will overflow and underflow int values.

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;
4

Easy way to wrap your head around it: we have an even number of bits to store a number in. We define 0 as the "middle" point of a range of even numbers. There has to be a difference of 1 either on the positive or negative side of 0 because the middle point is an odd amount in an even set of posible numbers.

Imagine having 8 bits integers. Where is the "most middle" point of that? Either the forth or fifth bit:

00010000 //3 bits on the "positive side", 4 bits on the "negative side" 
00001000 //4bits positive, 3 bits negative
4
  • This is a much "deeper" answer than the "Java will overflow" answer.
    – user949300
    May 28, 2018 at 5:34
  • I guess.. What are you saying?
    – fstam
    May 28, 2018 at 7:42
  • I think most people would expect MIN_VALUE - MAX_VALUE to equal 0. Why do they different by 1? Because of 0.
    – user949300
    May 28, 2018 at 13:11
  • You have to first subtract 1 from MIN_VALUE to underflow and get MAX_VALUE. So when you then subtract the remaining (MAX_VALUE-1) from MAX_VALUE you obviously get 1. May 29, 2018 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.