Total of Long Integers with Varargs in Java


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

  • The class LongTotalCalculator contains a single static method calculateTotal that takes a variable number of long values using varargs.
  • It first checks if any numbers are provided. If not, it throws an IllegalArgumentException.
  • It then initializes a variable total to zero.
  • It iterates over each long value in the numbers array and adds it to the total.
  • Finally, it returns the total.
  • In the main method, the calculateTotal method is called with three long values (1000000L, 2000000L, and 3000000L) to demonstrate its functionality. The result is printed to the console.

Source Code

public class LongTotalCalculator
{
	static long calculateTotal(long... numbers)
	{
		if (numbers.length == 0)
		{
			throw new IllegalArgumentException("No numbers provided");
		}
		long total = 0;
		for (long num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	public static void main(String[] args)
	{
		long total = calculateTotal(1000000L, 2000000L, 3000000L);
		System.out.println("Total : " + total);
	}
}

Output

Total : 6000000

Example Programs