Method Overloading in Java to Find Arithmetic Sum of 2 or 3 or 4 Variables by Passing Argument

Method Overloading in Java to Find Arithmetic Sum of 2 or 3 or 4 Variables by Passing Argument. This is a Java program that uses method overloading to find the arithmetic sum of two, three, or four variables. Overloaded methods are two or more methods inside the same class that have the same name but distinct argument declarations, and the practise is known as method overloading. We’ve created a class with three methods, each with the same name but a different number of parameters. Now, depending on the amount of parameters supplied, various methods can be called. As a result, we receive three different output values.

public class Main
{
int add(int a, int b)
{
int sum;
sum = a + b;
return sum;
}
int add(int a, int b, int c)
{
int sum;
sum = a + b + c;
return sum;
}
int add(int a, int b, int c, int w)
{
int sum;
sum = a + b + c + w;
return sum;
}
public static void main(String[] args)
{
Main obj = new Main();
int a = obj.add(100, 150);
System.out.println("Sum with two arguments"+a);
int b = obj.add(50, 100, 150);
System.out.println("Sum with three arguments"+b);
int c = obj.add(100, 150, 200, 250);
System.out.println("Sum with four arguments"+c);
}
}

 

Output:

Sum with two arguments 250
Sum with three arguments 300
Sum with four arguments 700