How can I detect integer overflow on 32 bits int?

ashur picture ashur · Jan 20, 2014 · Viewed 34.4k times · Source

I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:

  11111111111111111111111111111111 +
  00000000000000000000000000000001 =
  00000000000000000000000000000000   //overflow!

I found topic with similar question about this, however the algorithm is not perfect.

  11111111111111111111111111111111 +
  00000000000000000000000000000000 =
  00000000000000000000000000000000  //overflow!

Is there any simple, fast, safer way to check this ?

Answer

Patryk Czarnik picture Patryk Czarnik · Feb 7, 2018

Math.addExact throws exception on overflow

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

…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