Java – Calculate Power of a Number Raised to Another Number

To calculate power of a number, you can either user Math function pow(), or use a for loop, to multiply the number given number of times.

Calculate Power of Number using Math.pow()

pow() takes two numbers as arguments and calculate the first argument raised to the power of second argument.

Java Program

/**
 * Java Program - Power of a Number
 */

public class Power {

	public static void main(String[] args) {
		//numbers
		int number = 5;
		int power = 3;
		double result = Math.pow(number, power);
		System.out.println(number + " raised to the power " + power + " = " +result);
	}
}

Output

5 raised to the power 3 = 125.0
ADVERTISEMENT

Calculate Power of Number using For Loop

You can use Java For Loop to calculate the result of a number raised to the power of another number.

Java Program

/**
 * Java Program - Power of a Number
 */

public class Power {

	public static void main(String[] args) {
		//numbers
		int number = 5;
		int power = 3;
		
		long result = 1;
		for (int i = 0; i < power; i++)
			result *= number;
		
		System.out.println(number + " raised to the power " + power + " = " +result);
	}
}

Output

5 raised to the power 3 = 125

Conclusion

In this Java Tutorial, we learned how to calculate the power of a number using Math library function or Java looping statements.