Method Overloading with Different Data Types, Varargs, and Changing Order of Parameters in Java


Create a Java program to demonstrate method overloading with different data types, varargs, and changing order of parameters

This Java program defines a class named Calculator with several overloaded sum methods. Overloading means having multiple methods with the same name but different parameter lists.

  • The main method creates an instance of the Calculator class.
  • It then calls the sum methods with different arguments.
  • The Java compiler determines which 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 results are then printed to the console.

Source Code

class Calculator
{
	int sum(int... numbers)
	{
		int total = 0;
		for (int num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	double sum(double a, double b)
	{
		return a + b;
	}
 
	double sum(double a, double b, double c)
	{
		return a + b + c;
	}
 
	public static void main(String[] args)
	{
		Calculator calc = new Calculator();
		System.out.println("Sum of Integers : " + calc.sum(3, 7, 5));
		System.out.println("Sum of Doubles : " + calc.sum(8.2, 3.7));
		System.out.println("Sum of Three Doubles : " + calc.sum(1.0, 2.0, 3.0));
	}
}

Output

Sum of Integers : 15.0
Sum of Doubles : 11.899999999999999
Sum of Three Doubles : 6.0

Example Programs