Integer Power Calculation with Varargs in Java


Create a Java program demonstrating a method with varargs that calculates the power of integers

  • The PowerCalculator class contains a static method named calculatePower that calculates the result of raising a base number to multiple exponents.
  • It takes two arguments: the base number (base) and an array of exponents (exponents).
  • Inside the method, it initializes a variable result to 1 to store the cumulative result.
  • It iterates through each exponent exp in the array of exponents.
  • For each exponent, it calculates the result by raising the base to the current exponent using Math.pow() method and multiplies it with the previous result.
  • After iterating through all exponents, it returns the final result.
  • In the main method, the calculatePower method is called with the base number 2 and exponents 3, 2, and 4.
  • The output will be the result of raising 2 to the power of 3, then raising the result to the power of 2, and finally raising the result to the power of 4. The final result is printed to the console.

Source Code

public class PowerCalculator
{
	static int calculatePower(int base, int... exponents)
	{
		int result = 1;
		for (int exp : exponents)
		{
			result *= Math.pow(base, exp);
		}
		return result;
	}
 
	public static void main(String[] args)
	{
		int power = calculatePower(2, 3, 2, 4);
		System.out.println("Power: " + power);
	}
}

Output

Power: 512

Example Programs