This program finds the sum of two, three and four numbers using method overloading. Here we have three methods with the same name add(), which means we are overloading this method. Based on the number of arguments we pass while calling add method will determine which method will be invoked.
To understand this program you should have the knowledge of following Core Java topic:
Java – Method Overloading
Example: Program to find the sum of multiple numbers using Method Overloading
First add() method has two arguments which means when we pass two numbers while calling add() method then this method would be invoked. Similarly when we pass three and four arguments, the second and third add method would be invoked respectively.
public class JavaExample { int add(int num1, int num2) { return num1+num2; } int add(int num1, int num2, int num3) { return num1+num2+num3; } int add(int num1, int num2, int num3, int num4) { return num1+num2+num3+num4; } public static void main(String[] args) { JavaExample obj = new JavaExample(); //This will call the first add method System.out.println("Sum of two numbers: "+obj.add(10, 20)); //This will call second add method System.out.println("Sum of three numbers: "+obj.add(10, 20, 30)); //This will call third add method System.out.println("Sum of four numbers: "+obj.add(1, 2, 3, 4)); } }
Output:
Sum of two numbers: 30 Sum of three numbers: 60 Sum of four numbers: 10
Leave a Reply