Method Overloading with Varargs in Java


Create a Java program to demonstrate method overloading with varargs

  • Class Definition: In this Java class named Calculator, a method named sum is defined. This method utilizes a variable number of arguments (varargs) denoted by int... numbers, which allows it to accept any number of integer arguments. Inside the sum method, a for loop iterates over each integer in the numbers array and accumulates their sum in the variable total. Finally, the method returns the total sum.
  • Main Method: The main method serves as the entry point of the program. Inside the main method, an instance of the Calculator class is created using the constructor new Calculator() and assigned to the variable calc.
  • Method Calls: Two method calls to the sum method are made from the main method. In the first call calc.sum(1, 2, 3), the sum method is invoked with three integer arguments: 1, 2, and 3. In the second call calc.sum(10, 20, 30, 40, 50), the sum method is invoked with five integer arguments: 10, 20, 30, 40, and 50.
  • Output: The results of the method calls are printed to the console using System.out.println(). The first print statement displays "Sum of 3 Numbers :" followed by the sum returned by calc.sum(1, 2, 3). Similarly, the second print statement displays "Sum of 4 Numbers :" followed by the sum returned by calc.sum(10, 20, 30, 40, 50).
  • Varargs Usage: The usage of varargs (int... numbers) in the sum method allows for flexibility in the number of arguments passed to the method. This enables concise and flexible method calls without the need to specify an array explicitly.

Source Code

class Calculator
{
	int sum(int... numbers)
	{
		int total = 0;
		for (int num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	public static void main(String[] args)
	{
		Calculator calc = new Calculator();
		System.out.println("Sum of 3 Numbers : " + calc.sum(1, 2, 3));
		System.out.println("Sum of 4 Numbers : " + calc.sum(10, 20, 30, 40, 50));
	}
}

Output

Sum of 3 Numbers : 6
Sum of 4 Numbers : 150

Example Programs