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 ?
Math.addExact
throws exception on overflowSince 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