Product of Doubles with Varargs in Java


Create a Java program using a method with varargs to calculate the product of doubles

  • The DoubleProductCalculator class has a static method named calculateProduct that takes a variable number of double parameters (numbers).
  • Inside the method, the given numbers are printed using Arrays.toString(numbers) to display them as a string.
  • If no numbers are provided (i.e., the length of the numbers array is 0), an IllegalArgumentException is thrown.
  • The method initializes a variable product to 1 and then iterates through each number in the numbers array, multiplying each number with the current product.
  • Finally, the computed product is returned.
  • In the main method, the calculateProduct method is called with three double numbers (2.5, 1.5, and 3.0), and the result is printed to the console.

Source Code

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

Output

Given Numbers : [2.5, 1.5, 3.0]
Product : 11.25

Example Programs