如果我将 Integer.MAX_VALUE + 1
参数传递给 method(int var)
,如何防止 int 溢出?
示例:
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);
}
}
最佳答案
您无法“阻止”溢出。这是显而易见的,因为 int
数据类型有一个值范围。使用+
运算符进行数字相加时,int + int
的结果是int
类型。
您想要做的可能是防止出现意外结果,在这种情况下您宁愿知道是否发生了溢出。为此,您可以使用:
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.
}
这样,您就可以处理溢出的情况并且不使用意外的值。但还是发生了溢出。
当您对此方法完成测试时:
Math.addExact(Integer.MAX_VALUE, 1)
引发以下异常:
java.lang.ArithmeticException thrown: integer overflow
at Math.addExact (Math.java:825)
您的另一个选择是使用long
来允许更大的值。为此,您需要将至少一个值转换为 long
:
(long)Integer.MAX_VALUE + 1
这会产生long
值2147483648
关于java - 将 Integer.MAX_VALUE+1 参数传递给方法时防止溢出 (int var),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50685183/