Java 如何处理整数下溢和溢出,您将如何检查它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3001836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:28:35  来源:igfitidea点击:

How does Java handle integer underflows and overflows and how would you check for it?

javaintegerinteger-overflow

提问by KushalP

How does Java handle integer underflows and overflows?

Java 如何处理整数下溢和上溢?

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

从那开始,您将如何检查/测试这种情况正在发生?

采纳答案by BalusC

If it overflows, it goes back to the minimum valueand continues from there. If it underflows, it goes back to the maximum valueand 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 intby longto perform the same checks for long)

(您可以替换intlong对 执行相同的检查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. longor maybe java.math.BigInteger. The last one doesn't overflow, practically, the available JVM memory is the limit.

如果您认为这种情况可能经常发生,请考虑使用可以存储更大值的数据类型或对象,例如longjava.math.BigInteger。最后一个不会溢出,实际上,可用的 JVM 内存是限制。



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 ArithmeticExceptionon overflow.

如果您碰巧已经在 J​​ava8 上,那么您可以使用 newMath#addExact()Math#subtractExact()方法,这将引发ArithmeticException溢出。

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 hereand hererespectively.

可以分别在此处此处找到源代码。

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

当然,您也可以立即使用它们,而不是将它们隐藏在boolean实用程序方法中。

回答by Sean Owen

It doesn't do anything -- the under/overflow just happens.

它没有做任何事情——下溢/上溢就发生了。

A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.

作为溢出计算结果的“-1”与由任何其他信息产生的“-1”没有区别。因此,您无法通过某种状态或仅检查一个值来判断它是否已溢出。

But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?

但是你可以对你的计算很聪明,以避免溢出,如果它很重要,或者至少知道它什么时候会发生。你是什​​么情况?

回答by Peter Tillemans

It wraps around.

它环绕。

e.g:

例如:

public class Test {

    public static void main(String[] args) {
        int i = Integer.MAX_VALUE;
        int j = Integer.MIN_VALUE;

        System.out.println(i+1);
        System.out.println(j-1);
    }
}

prints

印刷

-2147483648
2147483647

回答by Durandal

Well, as far as primitive integer types go, Java doesnt handle Over/Underflow at all (for float and double the behaviour is different, it will flush to +/- infinity just as IEEE-754 mandates).

好吧,就原始整数类型而言,Java 根本不处理上溢/下溢(对于 float 和 double 行为是不同的,它将刷新到 +/- 无穷大,就像 IEEE-754 的要求一样)。

When adding two int's, you will get no indication when an overflow occurs. A simple method to check for overflow is to use the next bigger type to actually perform the operation and check if the result is still in range for the source type:

添加两个 int 时,在发生溢出时您不会得到任何指示。检查溢出的一个简单方法是使用下一个更大的类型来实际执行操作并检查结果是否仍在源类型的范围内:

public int addWithOverflowCheck(int a, int b) {
    // the cast of a is required, to make the + work with long precision,
    // if we just added (a + b) the addition would use int precision and
    // the result would be cast to long afterwards!
    long result = ((long) a) + b;
    if (result > Integer.MAX_VALUE) {
         throw new RuntimeException("Overflow occured");
    } else if (result < Integer.MIN_VALUE) {
         throw new RuntimeException("Underflow occured");
    }
    // at this point we can safely cast back to int, we checked before
    // that the value will be withing int's limits
    return (int) result;
}

What you would do in place of the throw clauses, depends on your applications requirements (throw, flush to min/max or just log whatever). If you want to detect overflow on long operations, you're out of luck with primitives, use BigInteger instead.

你会做什么来代替 throw 子句,取决于你的应用程序要求(抛出、刷新到最小/最大或只是记录任何东西)。如果您想检测长时间操作的溢出,那么您对原语不走运,请改用 BigInteger。



Edit (2014-05-21): Since this question seems to be referred to quite frequently and I had to solve the same problem myself, its quite easy to evaluate the overflow condition by the same method a CPU would calculate its V flag.

编辑(2014-05-21):由于这个问题似乎经常被提及,而且我必须自己解决同样的问题,因此很容易通过 CPU 计算其 V 标志的相同方法来评估溢出条件。

Its basically a boolean expression that involves the sign of both operands as well as the result:

它基本上是一个布尔表达式,涉及两个操作数的符号以及结果:

/**
 * Add two int's with overflow detection (r = s + d)
 */
public static int add(final int s, final int d) throws ArithmeticException {
    int r = s + d;
    if (((s & d & ~r) | (~s & ~d & r)) < 0)
        throw new ArithmeticException("int overflow add(" + s + ", " + d + ")");    
    return r;
}

In java its simpler to apply the expression (in the if) to the entire 32 bits, and check the result using < 0 (this will effectively test the sign bit). The principle works exactly the same for all integer primitive types, changing all declarations in above method to long makes it work for long.

在 java 中,将表达式(在 if 中)应用于整个 32 位更简单,并使用 < 0 检查结果(这将有效地测试符号位)。对于所有整数原始类型,原理完全相同,将上述方法中的所有声明更改为 long 使其可以长时间工作。

For smaller types, due to the implicit conversion to int (see the JLS for bitwise operations for details), instead of checking < 0, the check needs to mask the sign bit explicitly (0x8000 for short operands, 0x80 for byte operands, adjust casts and parameter declaration appropiately):

对于较小的类型,由于隐式转换为 int(有关按位操作的详细信息,请参阅 JLS),而不是检查 < 0,检查需要显式屏蔽符号位(短操作数为 0x8000,字节操作数为 0x80,调整强制转换和适当的参数声明):

/**
 * Subtract two short's with overflow detection (r = d - s)
 */
public static short sub(final short d, final short s) throws ArithmeticException {
    int r = d - s;
    if ((((~s & d & ~r) | (s & ~d & r)) & 0x8000) != 0)
        throw new ArithmeticException("short overflow sub(" + s + ", " + d + ")");
    return (short) r;
}

(Note that above example uses the expression need for subtractoverflow detection)

(注意上面的例子使用了需要减法溢出检测的表达式)



So how/why do these boolean expressions work? First, some logical thinking reveals that an overflow can onlyoccur if the signs of both arguments are the same. Because, if one argument is negative and one positive, the result (of add) mustbe closer to zero, or in the extreme case one argument is zero, the same as the other argument. Since the arguments by themselves can'tcreate an overflow condition, their sum can't create an overflow either.

那么这些布尔表达式如何/为什么起作用?首先,一些逻辑思考表明,只有当两个参数的符号相同时才会发生溢出。因为,如果一个参数为负,一个为正,则(add)的结果必须更接近于零,或者在极端情况下,一个参数为零,与另一个参数相同。由于参数本身不能创建溢出条件,它们的总和也不能创建溢出。

So what happens if both arguments have the same sign? Lets take a look at the case both are positive: adding two arguments that create a sum larger than the types MAX_VALUE, will always yield a negative value, so an overflow occurs ifarg1 + arg2 > MAX_VALUE. Now the maximum value that could result would be MAX_VALUE + MAX_VALUE (the extreme case both arguments are MAX_VALUE). For a byte (example) that would mean 127 + 127 = 254. Looking at the bit representations of all values that can result from adding two positive values, one finds that those that overflow (128 to 254) all have bit 7 set, while all that do not overflow (0 to 127) have bit 7 (topmost, sign) cleared. Thats exactly what the first (right) part of the expression checks:

那么如果两个参数具有相同的符号会发生什么?让我们看一下两者都是正数的情况:添加两个参数创建的总和大于类型 MAX_VALUE,将始终产生负值,因此如果arg1 + arg2 > MAX_VALUE会发生溢出。现在可能产生的最大值是 MAX_VALUE + MAX_VALUE(极端情况下两个参数都是 MAX_VALUE)。对于意味着 127 + 127 = 254 的字节(示例)。查看可以通过添加两个正值产生的所有值的位表示,发现溢出(128 到 254)的那些都设置了第 7 位,而所有不溢出(0 到 127)的第 7 位(最顶层,符号)都被清除。这正是表达式的第一(右)部分检查的内容:

if (((s & d & ~r) | (~s & ~d & r)) < 0)

(~s & ~d & r) becomes true, only if, both operands (s, d) are positive and the result (r) is negative (the expression works on all 32 bits, but the only bit we're interested in is the topmost (sign) bit, which is checked against by the < 0).

(~s & ~d & r) 变为真,仅当,两个操作数 (s, d) 为正且结果 (r) 为负(该表达式适用于所有 32 位,但我们感兴趣的唯一位是最高(符号)位,由 < 0 进行检查。

Now if both arguments are negative, their sum can never be closer to zero than any of the arguments, the sum mustbe closer to minus infinity. The most extreme value we can produce is MIN_VALUE + MIN_VALUE, which (again for byte example) shows that for any in range value (-1 to -128) the sign bit is set, while any possible overflowing value (-129 to -256) has the sign bit cleared. So the sign of the result again reveals the overflow condition. Thats what the left half (s & d & ~r) checks for the case where both arguments (s, d) are negative and a result that is positive. The logic is largely equivalent to the positive case; all bit patterns that can result from adding two negative values will have the sign bit cleared if and only ifan underflow occured.

现在如果两个参数都是负数,它们的总和永远不会比任何一个参数更接近零,总和必须更接近负无穷大。我们可以产生的最极端值是 MIN_VALUE + MIN_VALUE,这(再次以字节为例)表明对于任何范围内的值(-1 到 -128),符号位被设置,而任何可能的溢出值(-129 到 -256 ) 已清除符号位。所以结果的符号再次揭示了溢出情况。这就是左半部分 (s & d & ~r) 检查两个参数 (s, d) 为负且结果为正的情况。逻辑在很大程度上等同于积极的情况;当且仅当发生下溢时,由两个负值相加产生的所有位模式都将清除符号位。

回答by Dusan

I think you should use something like this and it is called Upcasting:

我认为你应该使用这样的东西,它被称为 Upcasting:

public int multiplyBy2(int x) throws ArithmeticException {
    long result = 2 * (long) x;    
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
        throw new ArithmeticException("Integer overflow");
    }
    return (int) result;
}

You can read further here: Detect or prevent integer overflow

您可以在此处进一步阅读: 检测或防止整数溢出

It is quite reliable source.

这是相当可靠的来源。

回答by fragorl

Having just kinda run into this problem myself, here's my solution (for both multiplication and addition):

我自己刚刚遇到了这个问题,这是我的解决方案(乘法和加法):

static boolean wouldOverflowOccurwhenMultiplying(int a, int b) {
    // If either a or b are Integer.MIN_VALUE, then multiplying by anything other than 0 or 1 will result in overflow
    if (a == 0 || b == 0) {
        return false;
    } else if (a > 0 && b > 0) { // both positive, non zero
        return a > Integer.MAX_VALUE / b;
    } else if (b < 0 && a < 0) { // both negative, non zero
        return a < Integer.MAX_VALUE / b;
    } else { // exactly one of a,b is negative and one is positive, neither are zero
        if (b > 0) { // this last if statements protects against Integer.MIN_VALUE / -1, which in itself causes overflow.
            return a < Integer.MIN_VALUE / b;
        } else { // a > 0
            return b < Integer.MIN_VALUE / a;
        }
    }
}

boolean wouldOverflowOccurWhenAdding(int a, int b) {
    if (a > 0 && b > 0) {
        return a > Integer.MAX_VALUE - b;
    } else if (a < 0 && b < 0) {
        return a < Integer.MIN_VALUE - b;
    }
    return false;
}

feel free to correct if wrong or if can be simplified. I've done some testing with the multiplication method, mostly edge cases, but it could still be wrong.

如果错误或可以简化,请随时纠正。我已经用乘法方法做了一些测试,主要是边缘情况,但它仍然可能是错误的。

回答by Jim

Java doesn't do anything with integer overflow for either int or long primitive types and ignores overflow with positive and negative integers.

Java 不会对 int 或 long 原始类型的整数溢出做任何事情,并且会忽略正整数和负整数的溢出。

This answer first describes the of integer overflow, gives an example of how it can happen, even with intermediate values in expression evaluation, and then gives links to resources that give detailed techniques for preventing and detecting integer overflow.

这个答案首先描述了整数溢出,给出了它如何发生的例子,即使在表达式评估中使用中间值,然后提供指向资源的链接,这些资源提供了防止和检测整数溢出的详细技术。

Integer arithmetic and expressions reslulting in unexpected or undetected overflow are a common programming error. Unexpected or undetected integer overflow is also a well-known exploitable security issue, especially as it affects array, stack and list objects.

导致意外或未检测到溢出的整数算术和表达式是常见的编程错误。意外或未检测到的整数溢出也是众所周知的可利用的安全问题,尤其是当它影响数组、堆栈和列表对象时。

Overflow can occur in either a positive or negative direction where the positive or negative value would be beyond the maximum or minimum values for the primitive type in question. Overflow can occur in an intermediate value during expression or operation evaluation and affect the outcome of an expression or operation where the final value would be expected to be within range.

溢出可能发生在正或负方向,其中正值或负值将超出所讨论的基本类型的最大值或最小值。溢出可能发生在表达式或运算评估期间的中间值中,并影响最终值应在范围内的表达式或运算的结果。

Sometimes negative overflow is mistakenly called underflow. Underflow is what happens when a value would be closer to zero than the representation allows. Underflow occurs in integer arithmetic and is expected. Integer underflow happens when an integer evaluation would be between -1 and 0 or 0 and 1. What would be a fractional result truncates to 0. This is normal and expected with integer arithmetic and not considered an error. However, it can lead to code throwing an exception. One example is an "ArithmeticException: / by zero" exception if the result of integer underflow is used as a divisor in an expression.

有时负溢出被错误地称为下溢。下溢是当值比表示允许的更接近零时发生的情况。下溢发生在整数算术中并且是预期的。当整数计算介于 -1 和 0 或 0 和 1 之间时,就会发生整数下溢。小数结果会截断为 0。这是正常的,并且是整数算术的预期结果,不会被视为错误。但是,它可能导致代码抛出异常。一个示例是“ArithmeticException: / by zero”异常,如果整数下溢的结果用作表达式中的除数。

Consider the following code:

考虑以下代码:

int bigValue = Integer.MAX_VALUE;
int x = bigValue * 2 / 5;
int y = bigValue / x;

which results in x being assigned 0 and the subsequent evaluation of bigValue / x throws an exception, "ArithmeticException: / by zero" (i.e. divide by zero), instead of y being assigned the value 2.

这导致 x 被分配 0 并且随后对 bigValue / x 的评估抛出异常“ArithmeticException: / by zero”(即除以零),而不是 y 被分配值 2。

The expected result for x would be 858,993,458 which is less than the maximum int value of 2,147,483,647. However, the intermediate result from evaluating Integer.MAX_Value * 2, would be 4,294,967,294, which exceeds the maximum int value and is -2 in accordance with 2s complement integer representations. The subsequent evaluation of -2 / 5 evaluates to 0 which gets assigned to x.

x 的预期结果将是 858,993,458,它小于最大 int 值 2,147,483,647。但是,计算 Integer.MAX_Value * 2 的中间结果将是 4,294,967,294,这超出了最大 int 值并且根据 2s 补码整数表示为 -2。随后对 -2 / 5 的评估结果为 0,这将分配给 x。

Rearranging the expression for computing x to an expression that, when evaluated, divides before multiplying, the following code:

将用于计算 x 的表达式重新排列为一个表达式,该表达式在求值时先除以再乘以,如下代码:

int bigValue = Integer.MAX_VALUE;
int x = bigValue / 5 * 2;
int y = bigValue / x;

results in x being assigned 858,993,458 and y being assigned 2, which is expected.

结果 x 被分配了 858,993,458 并且 y 被分配了 2,这是预期的。

The intermediate result from bigValue / 5 is 429,496,729 which does not exceed the maximum value for an int. Subsequent evaluation of 429,496,729 * 2 doesn't exceed the maximum value for an int and the expected result gets assigned to x. The evaluation for y then does not divide by zero. The evaluations for x and y work as expected.

bigValue / 5 的中间结果是 429,496,729,它不超过 int 的最大值。429,496,729 * 2 的后续评估不会超过 int 的最大值,并且预期结果将分配给 x。然后对 y 的评估不除以零。x 和 y 的评估按预期工作。

Java integer values are stored as and behave in accordance with 2s complement signed integer representations. When a resulting value would be larger or smaller than the maximum or minimum integer values, a 2's complement integer value results instead. In situations not expressly designed to use 2s complement behavior, which is most ordinary integer arithmetic situations, the resulting 2s complement value will cause a programming logic or computation error as was shown in the example above. An excellent Wikipedia article describes 2s compliment binary integers here: Two's complement - Wikipedia

Java 整数值存储为并按照 2s 补码有符号整数表示形式运行。当结果值大于或小于最大或最小整数值时,会产生 2 的补码整数值。在没有明确设计为使用 2s 补码行为的情况下,这是最普通的整数算术情况,产生的 2s 补码值将导致编程逻辑或计算错误,如上例所示。一篇优秀的维基百科文章在这里描述了 2s补码二进制整数:二进制补码 - 维基百科

There are techniques for avoiding unintentional integer overflow. Techinques may be categorized as using pre-condition testing, upcasting and BigInteger.

有一些技术可以避免无意的整数溢出。技术可以分类为使用前置条件测试、向上转换和 BigInteger。

Pre-condition testing comprises examining the values going into an arithmetic operation or expression to ensure that an overflow won't occur with those values. Programming and design will need to create testing that ensures input values won't cause overflow and then determine what to do if input values occur that will cause overflow.

前置条件测试包括检查进入算术运算或表达式的值,以确保这些值不会发生溢出。编程和设计需要创建测试以确保输入值不会导致溢出,然后确定如果出现会导致溢出的输入值该怎么办。

Upcasting comprises using a larger primitive type to perform the arithmetic operation or expression and then determining if the resulting value is beyond the maximum or minimum values for an integer. Even with upcasting, it is still possible that the value or some intermediate value in an operation or expression will be beyond the maximum or minimum values for the upcast type and cause overflow, which will also not be detected and will cause unexpected and undesired results. Through analysis or pre-conditions, it may be possible to prevent overflow with upcasting when prevention without upcasting is not possible or practical. If the integers in question are already long primitive types, then upcasting is not possible with primitive types in Java.

向上转换包括使用更大的原始类型来执行算术运算或表达式,然后确定结果值是否超出整数的最大值或最小值。即使使用向上转换,操作或表达式中的值或某些中间值仍然可能会超出向上转换类型的最大值或最小值并导致溢出,这也不会被检测到并会导致意外和不希望的结果。通过分析或先决条件,当没有向上转换的预防不可能或不可行时,可以通过向上转换来防止溢出。如果所讨论的整数已经是 long 原始类型,那么在 Java 中就不可能使用原始类型进行向上转换。

The BigInteger technique comprises using BigInteger for the arithmetic operation or expression using library methods that use BigInteger. BigInteger does not overflow. It will use all available memory, if necessary. Its arithmetic methods are normally only slightly less efficient than integer operations. It is still possible that a result using BigInteger may be beyond the maximum or minimum values for an integer, however, overflow will not occur in the arithmetic leading to the result. Programming and design will still need to determine what to do if a BigInteger result is beyond the maximum or minimum values for the desired primitive result type, e.g., int or long.

BigInteger 技术包括使用 BigInteger 进行算术运算或使用使用 BigInteger 的库方法的表达式。BigInteger 不会溢出。如有必要,它将使用所有可用内存。它的算术方法通常只比整数运算效率稍低。使用 BigInteger 的结果仍然有可能超出整数的最大值或最小值,但是在导致结果的算术中不会发生溢出。如果 BigInteger 结果超出所需原始结果类型(例如 int 或 long)的最大值或最小值,编程和设计仍需要确定要执行的操作。

The Carnegie Mellon Software Engineering Institute's CERT program and Oracle have created a set of standards for secure Java programming. Included in the standards are techniques for preventing and detecting integer overflow. The standard is published as a freely accessible online resource here: The CERT Oracle Secure Coding Standard for Java

卡内基梅隆软件工程研究所的 CERT 计划和 Oracle 为安全 Java 编程创建了一套标准。标准中包括防止和检测整数溢出的技术。该标准作为可免费访问的在线资源在此处发布:适用于 Java 的 CERT Oracle 安全编码标准

The standard's section that describes and contains practical examples of coding techniques for preventing or detecting integer overflow is here: NUM00-J. Detect or prevent integer overflow

描述和包含用于防止或检测整数溢出的编码技术的实际示例的标准部分在这里:NUM00-J。检测或防止整数溢出

Book form and PDF form of The CERT Oracle Secure Coding Standard for Java are also available.

还提供适用于 Java 的 CERT Oracle 安全编码标准的书籍形式和 PDF 形式。

回答by reprogrammer

There are libraries that provide safe arithmetic operations, which check integer overflow/underflow . For example, Guava's IntMath.checkedAdd(int a, int b)returns the sum of aand b, provided it does not overflow, and throws ArithmeticExceptionif a + boverflows in signed intarithmetic.

有一些库提供安全的算术运算,可以检查整数上溢/下溢。例如,Guava 的IntMath.checkedAdd(int a, int b)返回和的ab,前提是它不溢出,ArithmeticException如果a + b有符号int算术溢出则抛出。

回答by Jeffrey Bosboom

By default, Java's int and long math silently wrap around on overflow and underflow. (Integer operations on other integer types are performed by first promoting the operands to int or long, per JLS 4.2.2.)

默认情况下,Java 的 int 和 long math 会默默地环绕溢出和下溢。(根据JLS 4.2.2,通过首先将操作数提升为 int 或 long 来执行对其他整数类型的整数运算。)

As of Java 8, java.lang.Mathprovides addExact, subtractExact, multiplyExact, incrementExact, decrementExactand negateExactstatic methods for both int and long arguments that perform the named operation, throwing ArithmeticException on overflow. (There's no divideExact method -- you'll have to check the one special case (MIN_VALUE / -1) yourself.)

从Java 8中java.lang.Math提供addExactsubtractExactmultiplyExactincrementExactdecrementExactnegateExact两个int和长参数执行指定的操作,溢出抛出ArithmeticException静态方法。(没有divideExact 方法——您必须自己检查一个特殊情况(MIN_VALUE / -1)。)

As of Java 8, java.lang.Math also provides toIntExactto cast a long to an int, throwing ArithmeticException if the long's value does not fit in an int. This can be useful for e.g. computing the sum of ints using unchecked long math, then using toIntExactto cast to int at the end (but be careful not to let your sum overflow).

从 Java 8 开始,java.lang.Math 还提供toIntExact将 long 转换为 int,如果 long 的值不适合 int 则抛出 ArithmeticException。这对于例如使用未经检查的长数学计算整数的总和,然后toIntExact在最后使用to强制转换为 int 非常有用(但要小心不要让您的总和溢出)。

If you're still using an older version of Java, Google Guava provides IntMath and LongMathstatic methods for checked addition, subtraction, multiplication and exponentiation (throwing on overflow). These classes also provide methods to compute factorials and binomial coefficients that return MAX_VALUEon overflow (which is less convenient to check). Guava's primitive utility classes, SignedBytes, UnsignedBytes, Shortsand Ints, provide checkedCastmethods for narrowing larger types (throwing IllegalArgumentException on under/overflow, notArithmeticException), as well as saturatingCastmethods that return MIN_VALUEor MAX_VALUEon overflow.

如果您仍在使用旧版本的 Java,Google Guava 提供IntMath 和 LongMath静态方法用于检查加法、减法、乘法和幂运算(抛出溢出)。这些类还提供了计算MAX_VALUE溢出时返回的阶乘和二项式系数的方法(检查起来不太方便)。番石榴的原始工具类,SignedBytesUnsignedBytesShortsInts,提供checkedCast用于缩窄更大类型(上下溢/上溢,投掷抛出:IllegalArgumentException方法ArithmeticException),以及saturatingCast该方法返回MIN_VALUEMAX_VALUE上溢。

回答by user4267316

static final int safeAdd(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left > Integer.MAX_VALUE - right
                : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left + right;
}

static final int safeSubtract(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left < Integer.MIN_VALUE + right
                : left > Integer.MAX_VALUE + right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left - right;
}

static final int safeMultiply(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left > Integer.MAX_VALUE/right
                  || left < Integer.MIN_VALUE/right
                : (right < -1 ? left > Integer.MIN_VALUE/right
                                || left < Integer.MAX_VALUE/right
                              : right == -1
                                && left == Integer.MIN_VALUE) ) {
    throw new ArithmeticException("Integer overflow");
  }
  return left * right;
}

static final int safeDivide(int left, int right)
                 throws ArithmeticException {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
  return left / right;
}

static final int safeNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return -a;
}
static final int safeAbs(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return Math.abs(a);
}