Write a Java program to demonstrate method overloading with varargs and generic methods
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; } }
Sum of Integers : 15 Sum of Doubles : 17.5 Maximum String : cherry Maximum Integer : 50 Maximum Double : 4.5
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions