George12
George12

Reputation: 105

Java MAX and MIN value for integers

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

Answers (2)

indivisible
indivisible

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

Sergey Kalinichenko
Sergey Kalinichenko

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

Demo on ideone.

Upvotes: 4

Related Questions