Reputation: 105
Why is it that (Integer.MAX_VALUE-Integer.MIN_VALUE) = -1
?
If you do it on a calculator it becomes a larger positive number but in java it's -1
?
Upvotes: 2
Views: 2514
Reputation: 5012
Integer overflow. If you go outside the bounds of what an Integer can hold it loops back around the other side.
For example try Integer.MAX_VALUE + 1
and see what it gives you.
Upvotes: 4
Reputation: 726987
This happens because of the arithmetic overflow: MIN_VALUE
is a large negative, so subtracting it from MAX_VALUE
produces a positive number which is beyond the capacity of an int
.
If you would like to match the results that you get on a calculator, convert int
values to long
before subtraction:
long minInt = Integer.MIN_VALUE;
long maxInt = Integer.MAX_VALUE;
long diff = maxInt - minInt;
System.out.println(diff);
Upvotes: 4