Method Overloading with Different Parameter Types and a Combination of Varargs and Specific Methods in Java


Write a Java program to demonstrate method overloading with different parameter types and a combination of varargs and specific methods

  • In the main method, an instance of the MethodOverloadingDemo class is created.
  • Various sum methods of MethodOverloadingDemo are called with different arguments.
  • The sum method is overloaded to accept varargs, an array of doubles, and specific integers, allowing for the sum of integers and doubles to be calculated in different ways.
  • The appropriate overloaded methods are called based on the arguments passed, and the results are printed to the console.

Source Code

public class OverloadingWithVarargsAndSpecificMethodsDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo calculator = new MethodOverloadingDemo();
 
		int intSum1 = calculator.sum(1, 2, 3);
		int intSum2 = calculator.sum(2, 4, 6, 8, 10);
		double doubleSum = calculator.sum(new double[]{1.5, 2.5, 3.5, 4.5, 5.5});
 
		System.out.println("Sum of Three Integers : " + intSum1);
		System.out.println("Sum of Varargs Integers : " + intSum2);
		System.out.println("Sum of Double Array : " + doubleSum);
	}
}
class MethodOverloadingDemo
{    
	int sum(int... numbers)// Method to calculate the sum of integers using varargs
	{
		int total = 0;
		for (int num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	double sum(double[] numbers)// Method to calculate the sum of an array of doubles
	{
		double total = 0.0;
		for (double num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	int sum(int a, int b, int c)// Method to calculate the sum of three integers
	{
		return a + b + c;
	}
}

Output

Sum of Three Integers : 6
Sum of Varargs Integers : 30
Sum of Double Array : 17.5

Example Programs