Product of Integers using Varargs in Java


Write a Java program using a method with varargs to find the product of integers

  • The class ProductCalculator contains a single static method calculateProduct that takes a variable number of integers as input (using varargs).
  • Inside the calculateProduct method, it first prints the given numbers using Arrays.toString(numbers).
  • It then checks if the length of the numbers array is 0. If it is, it throws an IllegalArgumentException with the message "No numbers provided".
  • It initializes a variable product to 1, which will store the product of all the numbers.
  • It iterates over each number in the numbers array and multiplies it with the current value of product.
  • Finally, it returns the calculated product.
  • In the main method, the calculateProduct method is called with a list of integer values to demonstrate its functionality, and the result is printed.

Source Code

import java.util.Arrays;
public class ProductCalculator
{
	static int calculateProduct(int... numbers)
	{
		System.out.println("Given Numbers : " + Arrays.toString(numbers));
		if (numbers.length == 0)
		{
			throw new IllegalArgumentException("No numbers provided");
		}
		int product = 1;
		for (int num : numbers)
		{
			product *= num;
		}
		return product;
	}
 
	public static void main(String[] args)
	{
		int product = calculateProduct(1, 2, 3, 4, 5);
		System.out.println("Product : " + product);
	}
}

Output

Given Numbers : [1, 2, 3, 4, 5]
Product : 120

Example Programs