Exponentiation is a mathematical operation in which the base operand repeatedly multiplied exponent operand times. xy, also termed as x raised to the power n.
Various programming languages such as Python, Perl, and Lua provide exponent operators i.e **, ^ (x ** y, x ^ y).
Unlike Python, Java doesn’t have support for exponent operator, instead, it has a static method in the Math library, Math.pow(base, exponent).
The method is one of the simplest ways to calculate the exponent. It falls under the Math library, one needs to import it as java.lang.math, since, it‘s a static method that can be directly called using the class name.
Another way is, to use for loop or recursive method which calls itself until the exponent operand reaches 1. However, it is limited to exponent 1 or greater than 1.
Math.pow Method
Math.pow() is built-in method for exponential operation. It is a static method that resides in the Math library. It takes two parameters first, the base value, and the second one is exponent value. It returns double type as a result.
Syntax:
public static double pow(double a, double b);
Java program to calculate power of a number using pow() method
public class ExponentCalculate
{
public static void main(String[] args) {
double base = 3;
double power = 2;
System.out.println(Math.pow(base, power));
}
}
Output:
9.0
Using for loop
Another way to calculate the exponent is, to use for loop or looping statement in which the power operand is 1 or greater than one. In this, execute the for loop in a decrement manner until the exponent reaches 1.
Java program to calculate power of a number using for loop
public class ExponentOperator
{
public static void main (String[]args)
{
int base = 3;
int power = 2;
int result = 1;
for (; power >= 1; --power)
{
result = base * result;
}
System.out.println (result);
}
}
Using recursive method
A method that calls itself repeatedly until it reaches a satisfying condition is known as a recursive method. For exponential operation, a method calls recursively until the exponent operand’s value reaches 1. This method only works for power having 1 or greater than one.
Java program to calculate power of a number using recursive method
public class ExponentOperator
{
public static void main (String[]args)
{
int result = calculateExponent (3, 2, 1);
System.out.println (result);
}
public static int calculateExponent (int base, int power, int result)
{
if (power < 1)
{
return result;
}
result = base * result;
return calculateExponent (base, --power, result);
}
}
This post was last modified on July 4, 2022