Method Overloading with Different Parameter Counts and Varargs in Java


Write a Java program to demonstrate method overloading with different parameter counts and varargs

This Java program demonstrates method overloading in a class named Calculation, where multiple sum methods are defined to calculate the sum of different numbers. Let's break down the code:

  • The main method creates an instance of the Calculation class.
  • It then calls the sum methods with different numbers of arguments.
  • The Java compiler determines which overloaded method to call based on the number and type of arguments passed.
  • For each call to sum, the appropriate version of the method is invoked, and the result is returned.
  • The calculated sums are then printed to the console.

Source Code

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

Output

Sum of Two Numbers : 8
Sum of Three Numbers : 12
Sum of Four Numbers : 150

Example Programs