How to prevent integer overflow in Java code?

Michael picture Michael · Sep 1, 2012 · Viewed 31.4k times · Source

Possible Duplicate:
How can I check if multiplying two numbers in Java will cause an overflow?

Suppose I have a Java class method, which uses * and + operations.

int foo(int a, int b) {
  ... // some calculations with + and * 
}

How to make sure that no overflow occurs in foo?

I guess I can either use BigDecimal or replace all + and * with "wrappers" like:

int sum(int a, int b) {
   int c = a + b;
   if (a > 0 && b > 0 && c < 0) 
     throw new MyOverfowException(a, b)
   return c;
}

int prod(int a, int b) {
   int c = a * b;
   if (a > 0 && b > 0 && c < 0) 
     throw new MyOverfowException(a, b)
   return c;
}

Are there better ways to make sure that no int overflow occurs in a Java method ?

Answer

Alnitak picture Alnitak · Sep 1, 2012

One way to check for an overflow is to have the operands promoted to a larger type (of double the original operand bit length) then perform the operation, and then see if the resulting value is too large for the original type, e.g.

int sum(int a, int b) {
    long r = (long)a + b;
    if (r >>> 32 != 0) {    // no sign extension
        throw new MyOverflowException(a, b);
    }
    return (int)r;
}

If your original type is a long, you'd have to use BigInteger as that larger type.