Java Math pow()

In this tutorial, we will learn about the Java Math.pow() method with the help of examples.

The pow() method returns the result of the first argument raised to the power of the second argument.


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

// computes 5 raised to the power 3 System.out.println(Math.pow(5, 3));
} } // Output: 125.0

Syntax of Math.pow()

That is, pow(a, b) = ab

The syntax of the pow() method is:

Math.pow(double num1, double num2)

Here, pow() is a static method. Hence, we are accessing the method using the class name, Math.

pow() Parameters

The pow() method takes two parameters.

  • num1 - the base parameter
  • num2 - the exponent parameter

pow() Return Values

  • returns the result of num1num2
  • returns 1.0 if num2 is zero
  • returns 0.0 if num1 is zero

Note: There are various special cases for the pow() method. To learn about all the special cases, visit Java Math.pow() Special Cases (Official Java Documentation).

Example: Java Math pow()

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

    // create a double variable
    double num1 = 5.0;
    double num2 = 3.0;

    // Math.pow() with positive numbers
System.out.println(Math.pow(num1, num2)); // 125.0
// Math.pow() with zero double zero = 0.0;
System.out.println(Math.pow(num1, zero)); // 0.0 System.out.println(Math.pow(zero, num2)); // 1.0
// Math.pow() with infinity double infinity = Double.POSITIVE_INFINITY;
System.out.println(Math.pow(num1, infinity)); // Infinity System.out.println(Math.pow(infinity, num2)); // Infinity
// Math.pow() with negative numbers
System.out.println(Math.pow(-num1, -num2)); // 0.008
} }

In the above example, we have used the Math.pow() with positive numbers, negative numbers, zero, and infinity.

Here, Double.POSITIVE_INFINITY is used to implement positive infinity in the program.

Note: When we pass an integer value to the pow() method, it automatically converts the int value to the double value.

int a = 2;
int b = 5;

Math.pow(a, b);   // returns 32.0

Recommended Tutorials

Did you find this article helpful?