The Java language is equipped with a comprehensive library for mathematical functions and operations. It is called "Math" class, and it resides in the java.lang package. There are methods included in the Math library for fundamental numerical operations, trigonometry, finding min-max, generating randoms, and logarithmic operations. In today's tutorial, we will focus on the Math.pow() method which is used to calculate the powers of numbers with respect to the base and the exponent. Let's get started. The expression ‘nth of power a’ can be mathematically written as an. We can define the terms in the expressions as follows. a - base n - exponent If we consider the exponent, we can identify it as the number that represents the number of times a multiplication is repeated. The base can be identified as the number that gets multiplied by itself.Using Math.pow() Method in Java - 1Let us now create a simple Java method to calculate the power of a number. Please note that in the following example, we are passing two arguments into the powerFunction() method, which are the base and the exponent, respectively.
public class Main {

   public static void main(String[] args) {
       int result = powerFunction(2, 5);
       System.out.println("2 raised to power of 5 = " + result);
   }

   static int powerFunction(int base, int exponent) {
       int result = 1;
       for (int i = 0; i < exponent; i++) {
           result = base * result;
       }
       return result;
   }
}
If we run the above example code, it would return 32. You might be imagining why we cannot simply write base^ exponent. It is because there is no power operator in Java that we can use with one line of code. Considering the above code, it’s obvious that we had to spend quite a bit of time writing this method. Moreover, if we were to calculate higher powers, it would take a considerable amount of time for these calculations to be finished as we are using for loops. In addition to that, loops would prevent us from performing power calculations with exponents with decimal numbers and the complexity of this method is not very favorable as there is more room for optimization. Considering how frequent exponentiation and other mathematical operations are used by programmers, the developers at Java back then created a library called ‘Math’, dedicated to facilitating mathematical operations. Therefore, instead of writing a power function from scratch, we can get the advantage of this library which is included in the Java Lang package.

What is the Math.pow method and how to do it?

Math.pow can be found in the java.lang package as a method in the Math library. It is used to calculate the power of numbers that are both integers as well as doubles. Let’s consider its syntax.
public static double pow(double base, double exponent)
As we can see in the syntax, the java.lang.Math.pow() method takes in two arguments. The first one is the base and the second one is the exponent. This would return baseexponent as its output. Let’s see how we can call it.

Raising a Number to a Power in Java using Math.pow

Let's find the answer to 54 using Math.pow.
import java.lang.Math;
public class MyClass{
    public static void main(String []args){
       double answer = Math.pow(5, 4);
// java.lang.Math.pow() method

       System.out.println("5 raised to power of 4 = " + answer);
    }
}
The output is 625.0. As you can see it’s a double value. If you are bothered by the decimal point, we can easily get rid of it by casting the number to an integer as follows. Note that we are changing the first line inside the main method.
int answer = (int) Math.pow(5, 4);
Now the result is 625. Let’s use fractional numbers for both base and exponent and try to get an answer. Let’s see what the value of 1.254.5 is.
import java.lang.Math;

public class MyClass {

   public static void main(String[] args) {
       double answer = Math.pow(1.25, 4.5);
// java.lang.Math.pow() method

       System.out.println("1.25 raised to power of 4.5 = " + answer);
   }
}
This would output 2.729575167846423. If you use a calculator, you will see that it returns the same answer. Let’s go through one more example before we move onto the next section. We will raise a number to a negative power and compare the results. For this example, we will pick 4 as the base and -2 as the exponent.
import java.lang.Math;

public class MyClass{

     public static void main(String []args){
        double answer = Math.pow(4, -2);
// java.lang.Math.pow() method

        System.out.println(answer);
     }
}
We would get the output as 0.0625.

Quick Example: How to Round Your Answer

Say, we need to find a value of 1.254.5. The answer is 2.729575167846423. Quite often it becomes necessary to round the result. Let's try to get an answer accurate to the fourth decimal place. How to do it? What if we only require the first 4 decimal places? We can use java.lang.Math.round method for that. However, as Math.round rounds the value to the nearest integer, we will have to multiply it by the number of decimal places and then round and divide again.
import java.lang.Math;

public class MyClass{

     public static void main(String []args){
        double answer = Math.pow(1.25, 4.5);
        answer = Math.round(answer*100.0)/100.0;

        System.out.println(answer);
     }

}
The output is 2.73.

How to Use Math.pow Properly

When we are using java.lang.Math.pow method, there are a few things to keep in mind.
  1. If the exponent parameter is zero, the output will be 1.0. This is because it is defined that the power of zero for any number is one.
  2. If the exponent parameter is one, the output will be the base parameter. This is because if you raise any number to the power of 1 mathematically, it will be the same as the base parameter.
  3. If the base is negative/positive zero and the exponent parameter is a negative number, it would result in Infinity. (Negative zeros can occur due to the rounding of numbers between zero and the smallest representable negative non-zero number).
  4. If the exponent parameter is NaN, the output will also be NaN.
Let’s consider one instance where the 3rd situation can happen.
import java.lang.Math;

public class MyClass{

     public static void main(String []args){
        double base = 5;
        double exponent = Double.NaN;

        double answer = Math.pow(base, exponent);

        System.out.println(answer);
     }
}
This would output NaN. Therefore, if your code results in NaN, it would be wise to check whether the exponent parameter is NaN. In case you are wondering what NaN is, it means ‘not a number’ and indicates that the value has not been defined. We believe that you are all set now to go ahead and apply lang.Math.pow() in your applications now.

Conclusion

java.lang.Math.pow() method is a great way to find the power of different numbers that are both integers as well as fractional values easily. Unlike a self-made method, it is highly optimized and well suited for a range of applications that are time-critical. Although it does output all the results as doubles, we can always cast the value into an integer like we did in the example. Moreover, for our convenience, java.lang.Math library provides methods to round it to the preferred number of decimal places. Using Math.pow() Method in Java - 2