This is a Java Program to Find Arithmetic Sum of 2 or 3 or 4 Variables by Passing Argument using Method Overloading. Two or more methods within the same class that share the same name but with different parameter declarations are called overloaded methods, and the process is referred to as method overloading.
Here we define a class with three different methods with same name but different number of parameters. Now these methods can be called depending upon the number of arguments passed. Hence we get three different values as output.
Here is the source code of the Java Program to Find Arithmetic Sum of 2 or 3 or 4 Variables by Passing Argument using Method Overloading. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Sum_Overloading
{
int add(int x, int y)
{
int sum;
sum = x + y;
return sum;
}
int add(int x, int y, int z)
{
int sum;
sum = x + y + z;
return sum;
}
int add(int x, int y, int z, int w)
{
int sum;
sum = x + y + z + w;
return sum;
}
public static void main(String[] args)
{
Sum_Overloading obj = new Sum_Overloading();
int a = obj.add(10, 15);
System.out.println("Sum with two arguments:"+a);
int b = obj.add(10, 15, 20);
System.out.println("Sum with three arguments:"+b);
int c = obj.add(10, 15, 20, 25);
System.out.println("Sum with four arguments:"+c);
}
}
Output:
$ javac Sum_Overloading.java $ java Sum_Overloading Sum with two arguments:25 Sum with three arguments:45 Sum with four arguments:70
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Information Technology MCQs
- Check Java Books
- Apply for Java Internship
- Check Programming Books
- Apply for Computer Science Internship