I have a problem when I add some number to the maximum of Integer, I am no longer above the maximum because the number changes to Integer.MIN_VALUE + added valued -1, how should I than check it ? `
int max = Integer.MAX_VALUE;
int x = max +100;
if (x > max){
System.out.println(x + "x is not bigger, so it wont be printed.");
}
}
}`
One way would be to test it as a long.
int max = 2292292;
int x = 100;
if ((x + (long)max) != (x + max)) {
System.out.println("Overflow on x so it wont be printed.");
} else {
x = max + 100;
}
There are a couple of methods depending on what you want to do.
If you are looking to add a number to an int
and want to know if it overflows, then use Math.addExact
. It throws an ArithmeticException
which you can catch if you want to take action.
If you want to safely add a value and then compare to Integer.MAX_VALUE
then use a long
instead. By definition no int
is ever larger than the maximum value.
So I'd suggest
try {
int x = Math.addExact(Integer.MAX_VALUE, 100);
} catch (ArithmeticException ex) {
System.out.println("x has overflowed");
}
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.