java 整数溢出检测,Java如何处理整数下溢和溢出以及如何检查它?

How does Java handle integer underflows and overflows?

Leading on from that, how would you check/test that this is occurring?

解决方案

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

You can check that beforehand as follows:

public static boolean willAdditionOverflow(int left, int right) {

if (right < 0 && right != Integer.MIN_VALUE) {

return willSubtractionOverflow(left, -right);

} else {

return (~(left ^ right) & (left ^ (left + right))) < 0;

}

}

public static boolean willSubtractionOverflow(int left, int right) {

if (right < 0) {

return willAdditionOverflow(left, -right);

} else {

return ((left ^ right) & (left ^ (left - right))) < 0;

}

}

(you can substitute int by long to perform the same checks for long)

If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. long or maybe java.math.BigInteger. The last one doesn't overflow, practically, the available JVM memory is the limit.

If you happen to be on Java8 already, then you can make use of the new Math#addExact() and Math#subtractExact() methods which will throw an ArithmeticException on overflow.

public static boolean willAdditionOverflow(int left, int right) {

try {

Math.addExact(left, right);

return false;

} catch (ArithmeticException e) {

return true;

}

}

public static boolean willSubtractionOverflow(int left, int right) {

try {

Math.subtractExact(left, right);

return false;

} catch (ArithmeticException e) {

return true;

}

}

The source code can be found here and here respectively.

Of course, you could also just use them right away instead of hiding them in a boolean utility method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值