Method Overloading In Java
If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method overloading increases the readability of the code or program.
There are two ways to obtain the Method Overloading:
- Changing the number of parameters
- Changing the datatype of parameters
Changing the number of parameters
In this concept, we have same method names with different number of parameters passing through the methods.
Overloading.java
class Overloading1
{
int num1;
int num2;
int num3;
int num4;
int add (int a, int b)
{
num1 = a;
num2 = b;
return (num1 + num2);
}
int add (int a, int b, int c)
{
num1 = a;
num2 = b;
num3 = c;
return (num1 + num2 + num3);
}
int add (int a, int b, int c, int d)
{
num1 = a;
num2 = b;
num3 = c;
num4 = d;
return (num1 + num2 + num3 + num4);
}
}
class Overloading
{
public static void main(String args[])
{
Overloading1 obj1 = new Overloading1 ();
System.out.println (obj1. add (22, 22));
System.out.println (obj1. add (5, 6, 7));
System.out.println (obj1. add (5, 6, 7, 8));
}
}
Output:

In the above code, add () is the method having different number of parameters once, it takes as two parameters i.e , int a and int b . It also takes three parameters i.e, int a, int b and int c. Here, num1, num2, num3 and num4 are instance variable the local variables a, b, c, d values are stored into instance variables after entering into methods. Here methods are non – static hence in program objects are created i.e, obj1. The methods are called by objects, hence they perform operations in methods and returns output to main method.
Changing the datatype of parameters
In this concept, the method names are same and they have same number of parameters passing through it. But the parameters are having different datatypes.
Parameter.java
class Overloading2
{
int add (int a, int b)
{
int num1 = a;
int num2 = b;
return (num1 + num2);
}
double add (double a, double b)
{
double num1 = a;
double num2 = b;
return (num1 + num2);
}
float add (float a, float b)
{
float num1 = a;
float num2 = b;
return (num1 + num2);
}
}
class Parameter
{
public static void main (String args[])
{
Overloading2 obj2 = new Overloading2 ();
System.out.println ("Datatype int sum :" + obj2. add (5, 5));
System.out.println ("Datatype Double sum :" + obj2. add (5.3, 5.6));
System.out.println ("Datatype float sum :" + obj2. add (5.4f, 5.2f));
}
}
Output:

In the above code, add is the method having same number of parameters, having different datatypes of parameters passing through the method. The various datatypes passing through the methods are int, float, double. Here the methods are instance methods, Hence the objects are created. These methods perform operations and returns output to the main method.