Search code examples
javaexceptioninteger-overflow

How to detect overflow on power in Java


I know that java.lang.Math provides a set of static methods to perform some operations (sum, difference, multiply, increment, decrement, negate, toInt), throwing an ArithmeticException on overflow.

Is there something similar for power?


Solution

  • No, there is nothing equivalent for pow built into Java. (The only pow methods built into Java are Math.pow, which accepts doubles and does not overflow in the same way integers do, and BigInteger.pow, which does not overflow because BigIntegers can be arbitrarily large.)

    If third-party libraries are acceptable, though, Guava has e.g. IntMath.checkedPow, which does what you're looking for.