Calculate the Power of Any Number in the Java Program

There are different ways of doing the same thing, especially when you are programming. In Java, there are several ways to do the same thing, and in this tutorial, various techniques have been demonstrated to calculate the power of a number.

Required Knowledge

To understand this lesson, the level of difficulty is low, but the basic understanding of Java arithmetic operators, data types, basic input/output and loop is necessary.

Used Techniques

In Java, three techniques are used primarily to find the power of any number. These are:

  1. Calculate the power of a number through while loop.
  2. Calculate the power of a number by through for loop.
  3. Calculate the power of a number by through pow() function.

To calculate the power of any number, the base number and an exponent are required.

Syntax:
Power of a number = baseexponent
Example:
In case of 23

The base number is 2
The exponent is 3
So, the power will be the result of 2*2*2
Output:
8

For the numerical input value, you can use predefined standard values, or take input from the user through scanner class, or take it through command line arguments.

Calculating the Power of a Number Through the While Loop in Java

Program:
public class ExampleProgram {

 public static void main(String[] args) {

  int basenumber = 2, exponent = 3;
  long temp = 1;

  while (exponent != 0) {
   temp *= basenumber;
   --exponent;
  }

  System.out.println("Result: " + temp);
 }
}
Output:
Result: 8
Explanation:
  • In the above program, the base number and exponent values have been assigned 2 and 3, respectively.
  • Using While Loop we keep multiplying temp by besanumber until the exponent becomes zero.
  • We have multiplied temp by basenumber three times, hence the result would be = 1 * 2 * 2 * 2 = 8.

Calculating the Power of a Number Through the For Loop in Java

Program:
public class ExampleProgram {

 public static void main(String[] args) {

  int basenumber = 2, exponent = 3;
  long temp = 1;

  for (;exponent != 0; --exponent) {
   temp *= basenumber;
  }

  System.out.println("Result: " + temp);
 }
}
Output:
Result: 8
Explanation:
  • In the above program, we used for loop instead of while loop, and the rest of the programmatic logic is the same.

Calculate the Power of a Number by Through pow() function

Program:
public class ExampleProgram {

 public static void main(String[] args) {

  int basenumber = 2, exponent = 3;
  double pow = Math.pow(basenumber, exponent);

  System.out.println("Result: " + pow);
 }
}
Output:
Result: 8.0
Explanation:
  • Above program used Math.pow() function and it's also capable of working with a negative exponent.

Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.