Java Program to Calculate the Power of a Number

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Calculate power of a number using a while loop

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

    int base = 3, exponent = 4;

    long result = 1;

    while (exponent != 0) {
      result *= base;
      --exponent;
    }

    System.out.println("Answer = " + result);
  }
}

Output

Answer = 81

In this program, base and exponent are assigned values 3 and 4 respectively.

Using the while loop, we keep on multiplying the result by base until the exponent becomes zero.

In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81.


Example 2: Calculate the power of a number using a for loop

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

    int base = 3, exponent = 4;

    long result = 1;

    for (; exponent != 0; --exponent) {
      result *= base;
    }

    System.out.println("Answer = " + result);
  }
}

Output

Answer = 81

Here, instead of using a while loop, we've used a for loop.

After each iteration, the exponent is decremented by 1, and the result is multiplied by the base exponent number of times.

Both programs above do not work if you have a negative exponent. For that, you need to use the pow() function in Java standard library.


Example 3: Calculate the power of a number using pow() function

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

    int base = 3, exponent = -4;
    double result = Math.pow(base, exponent);

    System.out.println("Answer = " + result);
  }
}

Output

Answer = 0.012345679012345678

In this program, we use Java's Math.pow() function to calculate the power of the given base.


We can also compute the power of a negative number using the pow() method.

Example 4: Compute Power of Negative Number

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

    // negative number
    int base = -3, exponent = 2;

    double result = Math.pow(base, exponent);
    System.out.println("Answer = " + result);
  }
}

Output

Answer = 9.0

Here, we have used the pow() method to compute the power of a negative number -3.


Also Read:

Before we wrap up, let’s put your knowledge of Java Program to Calculate the Power of a Number to the test! Can you solve the following challenge?

Challenge:

Write a function to calculate the power of a number.

  • The formula to calculate the power is given as: result = base ^ exponent.
  • Return the power of base raised to exponent.
  • For example, if base = 2 and exponent = 3, the expected output is 8.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges