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:
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)); } }
Sum of Two Numbers : 8 Sum of Three Numbers : 12 Sum of Four Numbers : 150
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions