Java Math pow()

pow() computes the first argument raised to the power of second argument.

Following is the syntax of pow() method.

double result = pow(double a, double b)

Since the definition of pow() function has double datatype for arguments, you can pass int, float or long as arguments as these datatypes will implicitly promote to double.

We shall learn about some of the special cases for pow() method with examples.

Example 1 – Math.pow(double, double)

In the following example, we use pow() method to compute a raised to the power of b, mathematically put ab.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double a = 5.2;
		double b = 3.1;
		double result = Math.pow(a, b);
		System.out.println(result);
	}
}

Output

165.80986483300362
ADVERTISEMENT

Example 2 – Math.pow(float, int)

In the following example, we will compute ab where a is of datatype float and b is of datatype int.

Java Program

public class MathExample {
	public static void main(String[] args) {
		float a = 5.2F;
		int b = 2;
		double result = Math.pow(a, b);
		System.out.println(result);
	}
}

Output

27.03999801635746

Both float and int are promoted to double, implicitly by Java. The same would hold for other datatypes.

Example 3 – Math.pow(a, b) – Raised to the Power Zero

If the second argument to pow() method, which is power, is zero, then pow() method would return 1.0.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double a = 5.2;
		double b = 0;
		double result = Math.pow(a, b);
		System.out.println(result);
	}
}

Output

1.0

Example 4 – Math.pow(a, b) – Power is One

If the second argument is 1.0, then pow() returns the first argument as is. Meaning a1.0 is a.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double a = 5.2;
		double b = 1.0;
		double result = Math.pow(a, b);
		System.out.println(result);
	}
}

Output

5.2

Even if the first argument is NaN, positive infinity, negative infinity, in this case whatever it is, pow() returns the first argument as is if second argument is one.

Conclusion

In this Java Tutorial, we learned about Java Math.pow() function, with example programs.