Method Overloading with Varargs and Generic Methods in Java


Write a Java program to demonstrate method overloading with varargs and generic methods

  • In the main method, an instance of the MethodOverloadingDemo class is created.
  • Various methods of MethodOverloadingDemo are called with different arguments.
  • The sum method is overloaded to accept both int and double varargs, allowing for the sum of integers and doubles to be calculated.
  • The findMax method is a generic method that finds the maximum of values of any type. It uses the Comparable interface to ensure that the type T is comparable.
  • The appropriate overloaded methods are called based on the arguments passed, and the results are printed to the console.

Source Code

public class OverloadingWithVarargsAndGenericsDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo calculator = new MethodOverloadingDemo();
 
		int intSum = calculator.sum(1, 2, 3, 4, 5);
		double doubleSum = calculator.sum(1.5, 2.5, 3.5, 4.5, 5.5);
 
		String maxString = calculator.findMax("apple", "banana", "cherry");
		Integer maxInteger = calculator.findMax(10, 20, 30, 40, 50);
		Double maxDouble = calculator.findMax(1.5, 2.5, 0.5, 3.5, 4.5);
 
		System.out.println("Sum of Integers : " + intSum);
		System.out.println("Sum of Doubles : " + doubleSum);
		System.out.println("Maximum String : " + maxString);
		System.out.println("Maximum Integer : " + maxInteger);
		System.out.println("Maximum Double : " + maxDouble);
	}
}
class MethodOverloadingDemo
{
	// Method to calculate the sum of integers using varargs
	int sum(int... numbers)
	{
		int total = 0;
		for (int num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	// Method to calculate the sum of doubles using varargs
	double sum(double... numbers)
	{
		double total = 0.0;
		for (double num : numbers)
		{
			total += num;
		}
		return total;
	}
 
	// Generic method to find the maximum of values of any type
	<T extends Comparable<T>> T findMax(T... values)
	{
		if (values.length == 0)
		{
			return null;
		}
 
		T max = values[0];
		for (T value : values)
		{
			if (value.compareTo(max) > 0)
			{
				max = value;
			}
		}
		return max;
	}
}

Output

Sum of Integers : 15
Sum of Doubles : 17.5
Maximum String : cherry
Maximum Integer : 50
Maximum Double : 4.5

Example Programs