Math pow() method usage with example in Java

java.lang. Math.pow() is used to calculate a number that is added to the power of other numbers. This function takes two arguments and returns the value of the first argument to the second argument. Some special cases are listed below:

  • If the second parameter is positive or negative zero, the result will be 1.0.
  • If the second parameter is 1.0, the result will be the same as the first parameter.
  • If the second parameter is NaN, then the result will also be NaN.

Grammar:

public static double pow(double a, double b)
Parameter:
a : this parameter is the base
b : this parameter is the exponent.
Return :
This method returns ab.

Example 1: The display works the java.lang.Math.pow() method.

//Java program to demonstrate working
//of java.lang.Math.pow() method
  
import java.lang.Math;
  
class Gfg {
  
     //driver code
     public static void main(String args[])
     {
         double a = 30 ;
         double b = 2 ;
         System.out.println(Math.pow(a, b));
  
         a = 3 ;
         b = 4 ;
         System.out.println(Math.pow(a, b));
  
         a = 2 ;
         b = 6 ;
         System.out.println(Math.pow(a, b));
     }
}

The output is as follows:

900.0
81.0
64.0

Example 2: Shows how java.lang.Math.pow() works when the parameter is NaN.

//Java program to demonstrate working
//of java.lang.Math.pow() method
import java.lang.Math; //importing java.lang package
  
public class GFG {
     public static void main(String[] args)
     {
  
         double nan = Double.NaN;
         double result;
  
         //Here second argument is NaN, //output will be NaN
         result = Math.pow( 2 , nan);
         System.out.println(result);
  
         //Here second argument is zero
         result = Math.pow( 1254 , 0 );
         System.out.println(result);
  
         //Here second argument is one
         result = Math.pow( 5 , 1 );
         System.out.println(result);
     }
}

The output is as follows:

NaN
1.0
5.0