java如何判断溢出
判断整数溢出的方法
在Java中,整数溢出不会抛出异常,但可以通过以下方法检测:
检查加法溢出

public static boolean isAddOverflow(int a, int b) {
if (b > 0 && a > Integer.MAX_VALUE - b) return true;
if (b < 0 && a < Integer.MIN_VALUE - b) return true;
return false;
}
检查乘法溢出
public static boolean isMultiplyOverflow(int a, int b) {
if (a == 0 || b == 0) return false;
if (a > 0) {
if (b > 0 && a > Integer.MAX_VALUE / b) return true;
if (b < 0 && b < Integer.MIN_VALUE / a) return true;
} else {
if (b > 0 && a < Integer.MIN_VALUE / b) return true;
if (b < 0 && b < Integer.MAX_VALUE / a) return true;
}
return false;
}
使用Math类的精确运算方法
Java 8+提供了Math类的精确运算方法,会抛出ArithmeticException异常:

try {
int result = Math.addExact(a, b);
// 或 Math.multiplyExact(a, b);
} catch (ArithmeticException e) {
// 处理溢出
}
使用BigInteger进行大数运算
对于需要保证精度的场景,可以使用BigInteger:
BigInteger bigA = BigInteger.valueOf(a);
BigInteger bigB = BigInteger.valueOf(b);
BigInteger sum = bigA.add(bigB);
if (sum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0 ||
sum.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {
// 处理溢出
}
位运算检测方法
通过比较运算前后的符号位变化检测溢出:
public static boolean isAddOverflowBitwise(int a, int b) {
int sum = a + b;
return ((a ^ sum) & (b ^ sum)) < 0;
}
这种方法利用了补码运算的特性,当两个正数相加结果为负,或两个负数相加结果为正时,说明发生了溢出。






