How can I prevent an int overflow, if I'm passing an Integer.MAX_VALUE + 1
parameter to a method(int var)
?
Example:
public class Hello {
void test(int var){
System.out.println(var);
}
public static void main(String[] args) {
Hello hello = new Hello();
hello.test(Integer.MAX_VALUE + 1);
}
}
答案 0 :(得分:2)
You cannot "prevent" the overflow. This is obvious because the int
data type has a value range. When adding numbers with the +
operator, the result of int + int
is of int
type.
What you want to do is perhaps prevent unexpected results, in which case you'd rather want to know that an overflow has occurred. For that, you can use:
try {
Math.addExact(a, b);
} catch(ArithmeticException ex) {
// If this exception is raised, then you know
// that an overflow occured, and you can handle it
// more appropriately.
}
With this, you can handle the case of an overflow and not use unexpected values. But the overflow still occurred.
When your test is done on this method:
Math.addExact(Integer.MAX_VALUE, 1)
The following exception is raised:
java.lang.ArithmeticException thrown: integer overflow
at Math.addExact (Math.java:825)
Your other option is to use long
to allow for larger values. For this, you'd need to cast at least one of the values to long
:
(long)Integer.MAX_VALUE + 1
This result in the long
value 2147483648
答案 1 :(得分:1)
You can only prevent the integer overflow/underflow at addition, by putting a check before the operation and moving to next bigger primitive datatype if required.
public class Hello {
public static void main(String[] args) {
Hello hello = new Hello();
int value = Integer.MAX_VALUE;
int toAdd = 1;
if (hello.isSafeAdd(value, toAdd)) {
hello.test(value + toAdd);
} else {
hello.test((long) value + toAdd);
}
}
boolean isSafeAdd(int value, int toAdd) {
return !(toAdd > 0 ? value > Integer.MAX_VALUE - toAdd : toAdd < Integer.MIN_VALUE - value);
}
void test(long var) {
System.out.println(var);
}
void test(int var) {
System.out.println(var);
}
}