Home »
Java »
Java Programs
Java program to implement method overloading based on the number of arguments
Learn how to implement method overloading based on the number of arguments in Java?
Submitted by Nidhi, on March 22, 2022
Problem statement
In this program, we will create 3 methods with the same name but all methods have a different number of arguments to calculate the sum of given arguments.
Source Code
The source code to implement method overloading based on the number of arguments is given below. The given program is compiled and executed successfully.
// Java program to implement method overloading
// based on the number of arguments
public class Main {
static int sum(int a, int b) {
int s = 0;
s = a + b;
return s;
}
static int sum(int a, int b, int c) {
int s = 0;
s = a + b + c;
return s;
}
static int sum(int a, int b, int c, int d) {
int s = 0;
s = a + b + c + d;
return s;
}
public static void main(String[] args) {
int result = 0;
result = sum(10, 20);
System.out.println("Sum : " + result);
result = sum(10, 20, 30);
System.out.println("Sum : " + result);
result = sum(10, 20, 30, 40);
System.out.println("Sum : " + result);
}
}
Output
Sum : 30
Sum : 60
Sum : 100
Explanation
In the above program, we created a Main class that contains a method main() and 3 overloaded method sum() to calculate the addition of a specified different number of arguments.
The main() method is the entry point for the program, here we called overloaded methods and printed the result.
Java Method Overloading Programs »