Java - What Is Math.pow() and How to Use It

Math.pow(double a, double b) is a static method of the Math class in Java. It takes two arguments (of type double) and raises the value of the first argument by the second argument i.e. a^b, and returns it as result (also double). In other words, a is the base and b is its exponent. For example, Math.pow(2,4) is equivalent to 2^4 or 16.

The return type Math.pow(...) is double. You can cast it to long or int (be careful of overflow for the latter.) Let’s look at some examples.

package com.codeahoy.ex;

import static java.lang.Double.NaN;

public class Main {
    public static void main(String[] args) {

        System.out.println((long) Math.pow(2, 4)); // 16

        System.out.println((long) Math.pow(2, 1)); // 2

        System.out.println((long) Math.pow(2, 0)); // 1

        // If the second argument is NaN, then the result is NaN.
        System.out.println(Math.pow(2, NaN)); // 0

        System.out.println(Math.pow(2.5, 3)); // 15.625
    }
}

Output

16
2
1
NaN
15.625

There you have it. Hope you found this tutorial useful!

Special cases

Here’s a truncated list of special cases for Math.pow(...), as documented in Javadocs.

For the complete list, please see Javadocs.

It’s worth noting that the Math class in Java contains several useful methods for arithmetic, logarithms and trignometric operations. The following YouTube video below talks about several methods of the Math class with examples. It’s a short video and I recommend that you watch it.

Please leave your comments below and like on Facebook or follow on Twitter to stay up-to-date.

comments powered by Disqus