Varargs Sum of Integers in Java


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

  • The class SumCalculator contains a single static method calculateSum, which takes a variable number of integers as input (using varargs).
  • Inside the calculateSum method, an enhanced for loop is used to iterate over each integer in the numbers array and add it to the sum variable.
  • After iterating over all the numbers, the total sum is returned.
  • In the main method, the calculateSum method is called with five integers (1, 2, 3, 4, 5) passed as arguments.
  • The result is then printed to the console, displaying the sum of the provided numbers.

Source Code

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

Output

Sum : 15

Example Programs