Java Program to Find Arithmetic Sum by Passing Argument Using Method Overloading

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.

  1. public class Sum_Overloading
  2. {
  3.     int add(int x, int y)
  4.     {
  5.         int sum;
  6.         sum = x + y;
  7.         return sum;
  8.     }
  9.     int add(int x, int y, int z)
  10.     {
  11.         int sum;
  12.         sum = x + y + z;
  13.         return sum;
  14.     }
  15.     int add(int x, int y, int z, int w)
  16.     {
  17.         int sum;
  18.         sum = x + y + z + w;
  19.         return sum;
  20.     }
  21.     public static void main(String[] args) 
  22.     {    
  23.         Sum_Overloading obj = new Sum_Overloading();
  24.         int a = obj.add(10, 15);
  25.         System.out.println("Sum with two arguments:"+a);
  26.         int b = obj.add(10, 15, 20);
  27.         System.out.println("Sum with three arguments:"+b);
  28.         int c = obj.add(10, 15, 20, 25);
  29.         System.out.println("Sum with four arguments:"+c);
  30.     }
  31. }

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
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.