Solution 1:

Math.addExact throws exception on overflow

Since Java 8 there is a set of methods in the Math class:

  • toIntExact(long)
  • addExact(int,int)
  • subtractExact(int,int)
  • multiplyExact(int,int)

…and versions for long as well.

Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range.

Example of addition:

int x = 2_000_000_000;
int y = 1_000_000_000;
try {
    int result = Math.addExact(x, y);
    System.out.println("The proper result is " + result);
} catch(ArithmeticException e) {
    System.out.println("Sorry, " + e);
}

See this code run live at IdeOne.com.

Sorry, java.lang.ArithmeticException: integer overflow

Solution 2:

long test = (long)x+y;
if (test > Integer.MAX_VALUE || test < Integer.MIN_VALUE)
   // Overflow!

Solution 3:

Try this way:

boolean isOverflow(int left, int right) {
    return right > 0
            ? Integer.MAX_VALUE - right < left
            : Integer.MIN_VALUE - right > left;
}

From: https://wiki.sei.cmu.edu/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow