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 ?