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 ?
To check for Integer overflow, we need to check the Integer. MAX_VALUE, which is the maximum value of an integer in Java. Let us see an example wherein integers are added and if the sum is more than the Integer. MAX_VALUE, then an exception is thrown.
Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.
You cannot detect overflow of a 32 bit number by using a 32 bit number. If it is unsigned it will always be understood as a number between 0 and 2^32 -1. A overflowing input would still result is a valid out. A signed 32 bit value would be "valid" in the range 0 - 2^31-1.
Overflow Detection – So overflow can be detected by checking Most Significant Bit(MSB) of two operands and answer. But Instead of using 3-bit Comparator Overflow can also be detected using 2 Bit Comparator just by checking Carry-in(C-in) and Carry-Out(C-out) from MSB's. Consider N-Bit Addition of 2's Complement number.
Math.addExact
throws exception on overflowSince 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With