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

isuru-buddhika
  • 289
  • 3
  • 9
  • Possible duplicate of [In Java, why does Integer.MIN\_VALUE == -Integer.MIN\_VALUE](https://softwareengineering.stackexchange.com/questions/348172/in-java-why-does-integer-min-value-integer-min-value) – Kilian Foth May 28 '18 at 07:32

2 Answers2

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;
Doc Brown
  • 199,015
  • 33
  • 367
  • 565
Ewan
  • 70,664
  • 5
  • 76
  • 161
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
fstam
  • 212
  • 2
  • 6