As a beginner, we often struggle to calculate the exponent of a number while doing Java programming.
In Java, we don’t have any direct operator for finding exponents. The most convenient way to calculate the exponent in Java is by using Math.pow()
function.
In this Java tutorial, you will learn two different ways to calculate exponents in Java with code examples.
1. Calculate exponent using Java for-loop
Basics are the building block for any programming language. So, we can simply use a for-loop and make our own logic in Java. Below is a Java program to do exponent of a number without Math.pow().
public class CalculateExponent1 {
public static void main(String[] args) {
//calculating exponent using for loop
int base=5;
int power=3;
int result=1;
if(power!=0){
for(int i=1;i<=power;i++)
{
result*=base;
}
}
System.out.println(base + " raise to " + power + " = " + result);
}
}
Output
5 rasise to 3 = 125
2. Java Math.pow() method to do exponents in Java
Java provides an inbuilt method to directly do exponents i.e Math.pow()
. The method simply accepts two parameters. Most importantly the two parameters must be of double type.

exponents in java Math.pow() method
Therefore, it is the most straightforward way of finding exponents in java.
The method returns the first parameter raised to the second parameter.
In addition, there are certain cases that programmers should know while using Math.pow() Java function.
- Firstly, If the second parameter is 0, the output will be 1.0
- Secondly, If the second parameter is 1.0, the output will be the first parameter.
- Finally, The result will be NaN if the second parameter is NaN.
Code Examples to calculate exponent in Java-
public class CalculateExponent {
public static void main(String[] args) {
double base=3;
double power=6;
Double result=0.0;
result=Math.pow(base, power);
System.out.println("result = "+result);
}
}
Output
result = 729.0
Case 1: Java Exponent when the second parameter is 0.
Double result=0.0;
result=Math.pow(9, 0);//when second parameter=0,result=1.0
System.out.println("result = "+result);
Output
result = 1.0
Case 2:Java Exponent when the second parameter is 1.0
Double result=0.0;
result=Math.pow(3, 1);
System.out.println("result = "+result);
Output
result = 3.0
Case 3:Java Exponent when the second parameter is NaN.
Double result=0.0;
result=Math.pow(3, Double.NaN);//when NaN
System.out.println("result = "+result);
Output
result = NaN
Changing the result of exponent from double to an integer type
Integer result=0;
result=(int)Math.pow(3, 6);
System.out.println("result = "+result);
Output
result = 729
More Java tutorials-
I you are learning Java programming you may want to get Java homework help from us.