Method Overloading in Java with Examples

If you start learning java, then one oops concept you will come across is Method Overloading. In this article, I will cover what is method overloading, different ways to achieve it, examples and rules to follow. But we first need to understand what is parameter.

Read Also : Difference between Method Overloading and Method Overriding

What are parameters?

Parameter is a variable in the method definition. When a method is called , the data of the arguments are passed to the method's parameter.  For example


Parameters in java

Now after understanding parameters , we come to our main question



What is Method Overloading

Class with methods having same name and different parameters (method signature) is called Method overloading.

Method overloading in java

To achieve Method overloading either you need to change number of parameters or type of parameters or order of parameters.


3 ways to Overload a method

1. Change number of parameters : By changing the number of parameters you can achieve method overloading.

For example :

add(int , int)       // two parameters
add(int, int, int) // three parameters

2. Data type of parameters :  Method overloading can be achieved by changing the  data type of parameters.

For example:

add(int , int)
add(int, float)

3. Order of parameters : Method overloading can be done by changing the order of parameters.

For example :

add(float , int)
add(int, float)


Changing Return Type of the Methods

If  two methods having the same name and  same parameters but different in return type, then program will throw compile time error.
Return type is not a part of the method signature. Hence, we can not achieve method overloading by changing the return type of the methods.

For example :

public int  anotherMethod(int, int)   // return type : int
public void anotherMethod(int, int) // return type : void

The above example is not a valid method overloading example. It will throw compile time error.

Method Overloading Examples

Below are some of examples of the Method Overloading. 

 1.   Overloading - Different number of Parameters

This example shows method overloading when there are different number of parameters.

class MethodOverloadingExample
{
     public void show(String s)
    {
      System.out.println(s);
    }
     public void show(int i , String s)
    {
      System.out.println(i + " " + s);
    }
}

public class Test 
{
     public static void main(String args[])
    {
      MethodOverloadingExample ol = new MethodOverloadingExample();
      ol.show("Be in Present");
      ol.show(10, "Be in Present");
    }
}

Output:
"Be in Present"
10 "Be in Present" 

In the above example, show() method is overloaded based on the number of parameters. Both show() methods have different parameters.One is accepting String type while other is accepting int and String parameters.

2. Overloading - Difference in Data types of Parameters


class MethodOverloadingExample
{
  public void show(String s)
 {
   System.out.println(s);
 }
  public void show(int i)
 {
   System.out.println(i + " " + s);
 }
}

public class Test
{
  public static void main(String args[])
 {
   MethodOverloadingExample ol = new MethodOverloadingExample();
   ol.show("Be in Present");
   ol.show(10);
 }
}

Output:
"Be in Present"
10

In the above example method overloading is done by changing the data type of the parameters.One show() method is accepting String parameter while other show() method is accepting int parameter.

3. Overloading -  Sequence of Data types of Parameters


class MethodOverloadingExample
{
  public void show(String s , int i)
 {
   System.out.println(s + " " + i);
 }
  public void show(int i , String s)
 {
   System.out.println(i + " " + s);
 }
}

public class Test
{
  public static void main(String args[])
 {
   MethodOverloadingExample ol = new MethodOverloadingExample();
   ol.show("Be in Present" ,10);
   ol.show(15 , "Alive is Awesome");
 }
} 

Output:
"Be in Present" 10
10 "Be in Present"

In the above example both show() methods have different sequence of data type of parameters. Since the first show method has parameters (int, String) second show method has parameters (String,int). The above case is a valid method overloading.

Can we Overload main() method in java?

Yes, we can overload the main method in java. Java program does not execute the overloaded main() method instead we need to call overloaded main() method from from the actual main() method only.

public class JavaHungry {
    public static void main(String args[]) {
        System.out.println("Inside actual main() method");
        //Calling main() overloaded method
        main("Calling overloaded main() method");
    }
    //Overloaded main method
    public static void main(String s) {
        System.out.println("Inside main() overloaded method");
    }
}

Output:
Inside actual main method
Inside main() overloaded method


Can we Overload Static Methods?

Yes, we can overload the static methods as well. We can have two or more static methods with same name and different parameters.

public class JavaHungry {
    public static void main(String args[]) {
        System.out.println("Inside static main() method");
        //Calling another static overloaded method
        anotherStaticMethod("Calling overloaded static method");
    }
    //Overloaded static method
    public static void anotherStaticMethod(String s) {
        System.out.println("Inside static overloaded method");
    }
}

Output:
Inside static main() method
Inside static overloaded method

Can we Overload methods that differ by static keyword only?

You can not overload methods which are differ by static keyword only (i.e having same method name and same method parameters)

public class JavaHungry { 
    public static void foo() { 
        System.out.println("foo() called "); 
    } 
    public void foo() { 
        // Compiler Error: method foo() is already defined in the class JavaHungry
        System.out.println("foo() without static"); 
    } 
    public static void main(String args[]) {  
        JavaHungry.foo(); 
    } 
} 

Output:
Compile time error

Does Java supports operator Overloading?

Java does not support user defined operator overloading. Internally java do support operator overloading. For example '+' operator. '+' operator is overloaded for concatenation.

Method Overloading and Type Promotion

Promoting smaller data type into bigger data type is known as type promotion. For example byte data type can be promoted to short data type or short data type can be promoted to int  data type.

What Type Promotion has to do with Method Overloading

Type promotion is an important concept. If you passed the values to a method which do not match the data types of the parameter, you may think that the program will throw compilation error. But that would not be the case and program will run fine because of Type promotion.

Type Promotion Table

Data type on the left side can be promoted to the any data type of the right side. For example, in the first line , byte can be promoted to any of the following data types short,int,long.

byte shortintlong
shortint long
int longfloatdouble
float double
long float double

Examples of Type Promotion

Example 1

public class TypePromotionExample {
    
    public static void main(String[] args) {
  TypePromotionExample obj = new TypePromotionExample(); 
/* Integer values are passed to the add method. Since there are no add method 
 * which accepts add(int,int). The integer values are automatically promoted to 
 * nearest bigger data type i.e long. So, add(long,long) method will be called. 
 */   
  obj.add(10, 10); 
 }

 void add(double a, double b) {
  System.out.println(a + b + " double");
 }

 void add(long a, long b) {
  System.out.println(a + b + " long");
 }

}

Output:
20 long


In the above example we have passed the int values (10,10)  to the add method. But there was no add(int,int) method in the program. int data type is automatically promoted to the nearest bigger data type i.e long and executed the method add(long,long)

Example 2

public class TypePromotionExample {
    
    public static void main(String[] args) {
 TypePromotionExample obj = new TypePromotionExample();
 obj.add(10, 10); // integer values are passed
 }

 void add(double a, double b) {
  System.out.println(a + b + " double");
 }

 void add(float a, float b) {
  System.out.println(a + b + " float");
 }

}

Output:
20.0  float

In the above example, we have passed the integer values (10,10) to the add method. But there is no add(int,int) method in the program. The data type of int values will automatically be promoted to the nearest bigger data type. In our case, add(float,float) will be preferred as compare to add(double,double). Reason is float is nearer to the int in type promotion. (Check the above type promotion table)

Example 3

public class TypePromotionExample {
    
    public static void main(String[] args) {
  TypePromotionExample obj = new TypePromotionExample();
  obj.add(10, 10); // integer values are passed
 }

 void add(double a, int b) {
  System.out.println(a + b + " double");
 }

 void add(long a, long b) {
  System.out.println(a + b + " long");
 }

}

Output
Compile Time Error

In the above example , compiler is not able to identify which method to execute as both of them are applicable after type promotion.

Few More Examples of Valid/Invalid Overloading

int method(int a, int b)

int method(float a, float b)

This is a valid overloading. Above, data type of parameters are different.

int method(int a , int b)

float method(int temp1,  int temp2)


This is not a valid overloading. Method overloading does not depend upon the return type. In parameters, both method has the exact same parameters. If you try to call any of the above method then compile time error will be thrown.

double method(int a , double b)

double method(double  x, int y)

This is a valid overloading. As the sequence of data types are different.

double method(int num)

double method(int x, int y)

This is a valid overloading.There are different number of parameters present in the given methods.
First method has one parameter while second method has two parameter.

int method(int a , int b , double c)

int method(int x, int y, double z)

This is not a valid overloading. It will throw compile time error as the parameters data type and sequence are exactly same.

Rules for Method Overloading

1. Must have different parameters list
2. May have different return types, if parameters list are also different
3. May have different access modifiers
4. May throw different exceptions

Method Overloading Coding Questions Example

1.  Return type is different , but method parameters and sequence are same

public class JavaHungry {
    public static void main(String args[]) {
        Addition obj = new Addition();
        obj.add(40,50);
        obj.add(30,10);
    }
}
class Addition{
    public int add(int a, int b) {
        System.out.println (a+b); 
        return (a+b);
 }
    public void add(int var1, int var2) {
        System.out.println(var1+var2+10);
    }
}

Answer: 
Compile time error , add method is already defined.

2.  Return type, method parameters and sequence are same

public class JavaHungry {
    public static void main(String args[]) {
        Addition obj = new Addition();
        obj.add(40,50);
        obj.add(30,10);
    }
}
class Addition{
    public void add(int a, int b) {
        System.out.println (a+b); 
        return (a+b);
 }
    public void add(int var1, int var2) {
        System.out.println(var1+var2+10);
    }
}

Answer: 
Compile time error , add method is already defined.

Points to Remember About Overloading

1. Polymorphism applies to overriding not to overloading.
2. Reference type determines which overloaded method will be used at compile time.

Overloaded Constructors

Overloading a constructor means typing in multiple versions of the constructor, each having a different parameter list , like the following examples:

class Foo{

  Foo() { }

  Foo(String s) { }

} 



About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry