简体   繁体   中英

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM