Sucks not having unsigned types, eh? But what do you want it to do if an overflow occurs? int by definition is bounded, and will eventually overflow with big enough a and b, no matter how hard you want it not to. Should it throw an exception if overflow occurs? Perhaps fall back to an overloaded version which uses BigInteger instead?
–
ThomasSep 1 '12 at 12:06

4 Answers
4

use of preconditions; i.e. range-check the inputs so that overflow is impossible,

doing each individual arithmetic operation using the next larger primitive integer type and explicitly checking for overflow, or

using BigInteger.

This Dr Dobbs article suggests creating a library of primitive arithmetic methods that do each primitive operation with an explicit overflow check. (You could view this as an implementation of bullet point #2 above.) But the authors go further by suggesting that you use bytecode rewriting to replace arithmetic bytecodes with calls to the equivalent methods which incorporate overflow checks.

Unfortunately, there is no way to enable overflow checking natively in Java. (But the same applies in lots of other languages; e.g. C, C++ ... )

"It is a difficult problem from an engineering perspective." -- It's not that difficult: just generate machine code to check the overflow register flag after every operation. That's what the C# "checked" block does. The issue is that Java doesn't offer that as an option, not because it is beyond the wit of man.
–
RichJan 21 '14 at 10:22

@Rich - it is difficult if you are not in a position to modify the Java compiler. Most people aren't!
–
Stephen CJan 21 '14 at 11:15

lol, good point :-) It's frustrating that this wasn't included in the Java compiler. There isn't a nice easy answer (which is also correct) on this question or it's duplicate :-(
–
RichJan 21 '14 at 11:18

Sum: Check whether b is larger than the difference of the maximum value you can store in int minus the value of a. If a and/or b can be negative, you must (i) be careful not to get an overflow already for the difference check and (ii) perform a similar check for the minimum.

Product: Thats more difficult. I would split the integers into two half-length integers (i.e. if int is 32 bit, split it into two 16 bit numbers using bit-masking and shifting). Then do the multiplication, and then look whether the result fits into 32 bit.

Everything under the condition that you do not want to simply take long for the temporary result.

Suppose both a and b are positive or negative, and if the sign of a + b is not equal with the sign of a and b, then overflow happens. You can use this rule to judge whether overflow happens and throw an exception. When you catch this expcetion, you can deal it according to the method metioned in previous answers.
Another method is to doing operation using largest range type which will not overflow. You can use long for the operation between Integers.