## What about Java integer addition overflow? Java 8 is still great!

osc_emo7t12i 2020-11-09 13:38:46

author ：Aaron_ tao

blog.csdn.net/qq_33330687/article/details/81626157

## problem

I met a problem when I was writing the question before , Need to be solved int How to judge whether overflow after adding , If it overflows, it returns Integer.MAX_VALUE

## Solution

JDK8 Has helped us to achieve Math Next , This method has to be StackOverflow Found it , It's really better than some domestic forums

``````public static int addExact(int x, int y) {
int r = x + y;
// HD 2-12 Overflow iff both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
``````

### Subtraction

`````` public static int subtractExact(int x, int y) {
int r = x - y;
// HD 2-12 Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if (((x ^ y) & (x ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
``````

### Multiplication

``````public static int multiplyExact(int x, int y) {
long r = (long)x * (long)y;
if ((int)r != r) {
throw new ArithmeticException("integer overflow");
}
return (int)r;
}
``````

Be careful long and int It's different

``````  public static long multiplyExact(long x, long y) {
long r = x * y;
long ax = Math.abs(x);
long ay = Math.abs(y);
if (((ax | ay) >>> 31 != 0)) {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if (((y != 0) && (r / y != x)) ||
(x == Long.MIN_VALUE && y == -1)) {
throw new ArithmeticException("long overflow");
}
}
return r;
}
``````

### How to use ？

Direct calls are the most convenient , But in pursuit of speed , It should be revised , Understanding judgment thinking , Because exceptions are very time-consuming operations , Without brain abnormalities, there is a possibility of overtime .

`````` Recommended reading
Code comparison tool , I'll use this 6 individual
Share my favorite 5 A free online  SQL Database environment , It's so convenient ！
Spring Boot A combination of three moves , Hand in hand to teach you to play elegant back-end interface
MySQL 5.7 vs 8.0, You choose the one ？ Net friend ： I'm going to stay where I am ~
``````
``````
Last , I recommend you an interesting and interesting official account ： The guy who wrote the code ,7 Old programmers teach you to write bug, reply interview | resources Send you a complete set of Development Notes There's a surprise
Sweep yards attention
``````