Sum of Cubes with Varargs in Java


Write a Java program using a method with varargs to calculate the sum of cubes of integers

This Java program computes the sum of the cubes of a set of numbers. It defines a method called calculateCubicSum, which takes in any number of integers and returns their cubic sum. The method iterates through each number in the input, cubes it (multiplies it by itself three times), and adds it to a running total. In the main method, it calls calculateCubicSum with the numbers 1, 2, 3, 4, and 5, and then prints out the result.

Source Code

public class CubicSumCalculator
{
	static int calculateCubicSum(int... numbers)
	{
		int sum = 0;
		for (int num : numbers)
		{
			sum += num * num * num;
		}
		return sum;
	}
 
	public static void main(String[] args)
	{
		int cubicSum = calculateCubicSum(1, 2, 3, 4, 5);
		System.out.println("Sum of Cubes : " + cubicSum);
	}
}

Output

Sum of Cubes : 225

Example Programs