BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Method Overloading in Java with examples

By Chaitanya Singh | Filed Under: java

Method Overloading is a feature that allows a class to have multiple methods with the same name but with different number, sequence or type of parameters. In short multiple methods with same name but with different signatures. For example the signature of method add(int a, int b) having two int parameters is different from signature of method add(int a, int b, int c) having three int parameters.

Method Overloading in Java

This is one of the most popular OOP feature in java, there are several cases where we need more than one methods with same name. For example let’s say we are writing a java program to find the sum of input numbers, we need different variants of add method based on the user inputs such as add(int, int), add(float, float) etc.

It is similar to constructor overloading in Java, that allows a class to have more than one constructor with different argument lists.

Three ways to overload a method

In order to overload a method, the parameter list of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading

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

2. Data type of parameters.
For example:

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

3. Sequence of Data type of parameters.
For example:

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

Invalid case of method overloading:
Parameters list doesn’t mean the return type of the method, for example if two methods have same name, same parameters and have different return type, then this is not a valid method overloading example. This will throw a compilation error.

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

Method overloading is an example of Static Polymorphism. We will discuss polymorphism and types of it in a separate tutorial.

Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.

Argument list vs parameter list: Argument list and parameter list are same but they are used in different context, when we declare a method, the parameters are called parameter list, while calling the method the argument we pass are called argument list.

Method Overloading examples

As discussed in the beginning of this guide, method overloading is done by declaring same method with different signatures. Let’s see some examples:

Example 1: Overloading – Different Number of parameters in signature

This example shows how method overloading is done by having different number of parameters. In this example, we have two methods with the same name add, but number of parameters are different. First variation of add() method has two int parameters, while the second variation of method add() has two int parameters.

class DisplayOverloading
{
  //adding two integer numbers
  int add(int a, int b)
  {
    int sum = a+b;
    return sum;
  }
  //adding three integer numbers
  int add(int a, int b, int c)
  {
    int sum = a+b+c;
    return sum;
  }
}
class JavaExample
{
  public static void main(String args[])
  {
    DisplayOverloading obj = new DisplayOverloading();
    System.out.println(obj.add(10, 20));
    System.out.println(obj.add(10, 20, 30));
  }
}

Output:

30
60

Example 2: Overloading – Data type of parameters are different

In this example, we are overloading the method add() based on the data type of parameters. We have two methods with the name add() but the type of parameters are different. The first variation of add() has two int params while the second variation of method add() has two float params.

class DisplayOverloading2
{
  //two int parameters
  public int add(int a, int b)
  {
    int sum = a+b;
    return sum;
  }
  //two float parameters
  public float add(float a, float b)
  {
    float sum = a+b;
    return sum;
  }
}

class JavaExample
{
  public static void main(String args[])
  {
    DisplayOverloading2 obj = new DisplayOverloading2();
    //This will call the method add with two int params
    System.out.println(obj.add(5, 15));

    //This will call the method add with two float params
    System.out.println(obj.add(5.5f, 2.5f));
  }
}

Output:

20
8.0

Example3: Overloading – Sequence of data type of parameters is different

In this example, the both the variations of method add() has same number of parameters but the sequence of data type of parameters is different.

First variation has (int, float) parameters and the second variation has (float, int) parameters. Since the sequence is different, the method can be overloaded without any issues.

class DisplayOverloading3
{
  public float add(int a, float b)
  {
    System.out.println("Method with (int, float) param list.");
    return a+b;
  }
  public float add(float a, int b)
  {
    System.out.println("Method with (float, int) param list.");
    return a+b;
  }
}
class JavaExample
{
  public static void main(String args[])
  {
    DisplayOverloading3 obj = new DisplayOverloading3();

    // This will call the method where first parameter is int
    // and the second parameter is float
    System.out.println(obj.add(10, 10.5f));

    // This will call the method where first parameter is float
    // and the second parameter is int
    System.out.println(obj.add(1.5f, 1));
  }
}

Output:

Method Overloading Example output

Method Overloading and Type Promotion

When a data type of smaller size is promoted to the data type of bigger size than this is called type promotion, for example: byte data type can be promoted to short, a short data type can be promoted to int, long, double etc.

What it has to do with method overloading?
Well, it is very important to understand type promotion else you will think that the program will throw compilation error but in fact that program will run fine because of type promotion.
Lets take an example to see what I am talking here:

class JavaExample{
  void disp(int a, double b){
    System.out.println("Method A");
  }
  void disp(int a, double b, double c){
    System.out.println("Method B");
  }
  public static void main(String args[]){
    JavaExample obj = new JavaExample();
    /* I am passing float value as a second argument but
     * it got promoted to the type double, because there
     * wasn't any method having arg list as (int, float)
     */
    obj.disp(100, 20.67f);
  }
}

Output:

Method A

As you can see in the above output, I had passed the second argument as float while calling the disp() method, however it got promoted to the double type as there wasn’t any method with argument list as (int, float)

But this type promotion doesn’t always happen, lets see another example:

class JavaExample{
  void disp(int a, double b){
    System.out.println("Method A");
  }
  void disp(int a, double b, double c){
    System.out.println("Method B");
  }
  void disp(int a, float b){
    System.out.println("Method C");
  }
  public static void main(String args[]){
    JavaExample obj = new JavaExample();
    /* This time promotion won't happen as there is
     * a method with parameter list as (int, float)
     */
    obj.disp(100, 20.67f);
  }
}

Output:

Method C

As you see that this time type promotion didn’t happen because there was a method with matching argument type.

Type Promotion table:

The data type on the left side can be promoted to any of the data type present at the right side.

byte → short → int → long → double
short → int → long → float → double
int → long → float → double
float → double
long → float → double
char → int → long → float → double

This can be represented as a diagram like this:

Method Overloading in Java

Lets see few Valid/invalid cases of method overloading

Case 1:

int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)

Result: Compile time error. Argument lists are exactly same. Both methods are having same number, data types and same sequence of data types.

Case 2:

int mymethod(int a, int b)
int mymethod(float var1, float var2)

Result: Perfectly fine. Valid case of overloading. Here, data types of arguments are different.

Case 3:

int mymethod(int a, int b)
int mymethod(int num)

Result: Perfectly fine. Valid case of overloading. Here number of arguments are different.

Case 4:

float mymethod(int a, float b)
float mymethod(float var1, int var2)

Result: Perfectly fine. Valid case of overloading. Sequence of the data types of parameters are different, first method is having (int, float) and second is having (float, int).

Case 5:

int mymethod(int a, int b)
float mymethod(int var1, int var2)

Result: Compile time error. Argument lists are exactly same. Even though return type of methods are different, it is not a valid case. Since return type of method doesn’t matter while overloading a method.

Guess the answers before checking it at the end of programs:
Question 1 – return type, method name and argument list same.

class Demo
{
   public int myMethod(int num1, int num2)
   { 
       System.out.println("First myMethod of class Demo");
       return num1+num2;
   }
   public int myMethod(int var1, int var2)
   {
       System.out.println("Second myMethod of class Demo");
       return var1-var2;
   }
}
class Sample4
{
   public static void main(String args[])
   {
       Demo obj1= new Demo();
       obj1.myMethod(10,10);
       obj1.myMethod(20,12);
   }
}

Answer:
It will throw a compilation error: More than one method with same name and argument list cannot be defined in a same class.

Question 2 – return type is different. Method name & argument list same.

class Demo2
{
   public double myMethod(int num1, int num2)
   {
      System.out.println("First myMethod of class Demo");
      return num1+num2;
   }
   public int myMethod(int var1, int var2)
   {
      System.out.println("Second myMethod of class Demo");
      return var1-var2;
   }
}
class Sample5
{
   public static void main(String args[])
   {
      Demo2 obj2= new Demo2();
      obj2.myMethod(10,10);
      obj2.myMethod(20,12);
   }
}

Answer:
It will throw a compilation error: More than one method with same name and argument list cannot be given in a class even though their return type is different. Method return type doesn’t matter in case of overloading.

Advantages of Method Overloading

  • Readability: It is not possible to have two methods with same name unless you are doing method overloading. Constantly looking for a unique method name for a similar task is quite a headache. It also impact the readability of the code. Method overloading solves this problem and improves readability of the code.
  • Structured Program: Improves the structure of overall program. Promotes the use of methods which reduces the lines of code significantly.
  • Reusability: Methods promotes reusability. Instead of writing same code again and again, define the code in method and call it whenever required.
  • Reduces code size: It reduces the number of lines of the code because of the improved program structure.

Method Overloading vs Overriding in Java

In Method Overloading , we have multiple methods with same name but with different signatures. In method Overriding, we define the same method with the same signature in the child class and change the body of the method. The differences are discussed in detail here.

Method Overloading vs Method Overriding

FAQ

1. Can we Overload a static method?

Yes we can overload a static method. However a non-static method cannot be overriden by a static method and vice versa. Refer this guide: Can static methods be overloaded or overriden in Java?

2. Can we overload main method of Java?

Yes, we can overload a main method. See the following example:

public class JavaExample {
  //Overloading main() methods
  //Here we have three variations of main() method
  public static void main(String[] args)
  {
    System.out.println("Main Method: String[] args");

    //calling main with one string param
    JavaExample.main("AA");

    //calling main with two string param
    JavaExample.main("BB", "CC");
  }

  // Overloaded main methods
  public static void main(String arg)
  {
    System.out.println("Main Method: String arg");
    System.out.println(arg);
  }
  public static void main(String arg, String arg2)
  {
    System.out.println("Main Method: String arg, String arg2");
    System.out.println(arg+" "+arg2);
  }
}

Output:

Main Method Overloading Output

3. Is there a concept of Operator overloading in Java?

No. Java doesn’t allow operator overloading. C++ however allows it. This is discussed here.

Recommended Posts

  • Overloading with Auto-boxing and Widening in Java
  • Overloading a method with Varargs Parameter
  • Method Overloading – Passing Null Values
❮ PreviousNext ❯

Comments

  1. sirisha says

    August 27, 2014 at 3:56 PM

    Very clear. Excellent examples. Thanks a lot

    Reply
  2. sweety says

    October 13, 2014 at 6:38 PM

    Thanks.. very good and easy to understand

    Reply
  3. Syed Munir Uddin says

    October 23, 2014 at 1:42 PM

    Excellent Example keep it up and thanks :-)

    Reply
  4. vishal says

    November 13, 2014 at 3:45 PM

    very clear….

    Reply
  5. prerana says

    November 13, 2014 at 9:40 PM

    The examples helped very much. The examples were clear, and to the point. Great explanation. :D

    Reply
  6. Mayur says

    January 4, 2015 at 9:12 AM

    Very well presentation. Thanks a lot.

    Reply
  7. Leesa says

    January 28, 2015 at 3:56 PM

    The case 4-
    float mymethod(int a, float b)
    float mymethod(float var1, int var2)
    causes a compilation error due to implicit method invocation datatype conversion. Please check ..

    Reply
    • Shipra says

      June 15, 2016 at 11:27 AM

      that’s right

      Reply
    • hayenadeblue says

      November 23, 2016 at 12:30 PM

      I think what is written in the article is correct. Don’t understand why Shipra agrees.

      Reply
      • Rajan Gupta says

        February 8, 2017 at 7:05 PM

        This is throwing compilation error because you might be passing integer values in both the methods…if you specifically pass float then this will not throw compilation error
        Something like this:
        mymethod(1.0f, 10);
        mymethod(1, 10.0f);
        I hope this helps.

        Reply
  8. Noah says

    March 6, 2015 at 7:52 PM

    There couldn’t be a more detailed and useful explanation of method overloading than this.

    Thank you!

    Reply
  9. chetan says

    March 10, 2015 at 5:41 AM

    You have described in well manner i like that your presentation way………….Please post more on same way………:)Thanks

    Reply
    • ANKUSH PAWAR says

      June 20, 2016 at 11:25 AM

      Thank you so much…simple and useful explanation

      Reply
  10. Kalhan says

    March 16, 2015 at 4:58 PM

    Thank you so much…simple and useful explanation

    Reply
  11. Suresh says

    March 28, 2015 at 5:43 PM

    Nice Example

    Reply
  12. Arpitha says

    April 9, 2015 at 6:38 AM

    Good Explanation :)

    Thank you

    Reply
  13. surekha says

    July 15, 2015 at 9:48 AM

    When should use dynamic binding..Please explain clearly..

    Reply
  14. sam says

    July 16, 2015 at 10:32 AM

    HI,
    In the below
    Case 4:

    float mymethod(int a, float b)
    float mymethod(float var1, int var2)
    Result: Perfectly fine. Valid case for overloading. Sequence of the data types are different, first method is having (int, float) and second is having (float, int).
    It will get ambiguity.

    Reply
    • Aravind Reddy says

      December 2, 2015 at 4:12 AM

      Yes there is an ambiguity in case:4
      Because int can be implicitly converted into float.
      So the compiler is in a confused state to which method it should bind to

      Reply
  15. Ganesh NB says

    August 3, 2015 at 11:24 AM

    Great Explanation. Can u make it clear wheather java supports pass by reference.I know its no. still the value are updated in the calling function. can you explain how it occurs…?

    Thank you in advance for the answer

    Reply
  16. saad ismail says

    February 26, 2016 at 7:27 PM

    perfectly explain i,m loving it my all concepts are clear ….

    Reply
  17. Kemoji says

    March 1, 2016 at 6:08 AM

    Wonderful… Super cool stuff, made things easy…Thanks a Ton

    Reply
  18. Md Nehaluddin Haider says

    March 6, 2016 at 5:16 AM

    I tried reading many tutorials for OOPs and now I can say this is the best. Thank you so much buddy for this wonderful tutorial.

    Reply
  19. Ankit says

    April 13, 2016 at 9:57 AM

    Best Example everything is clear..
    Good Job

    Thanks

    Reply
  20. Jeremiah Nji says

    May 5, 2016 at 1:11 PM

    This was perfect! You explained it so clearly. Overloading is something I comprehend completely now!

    Thank you!

    Reply
  21. akshay says

    June 8, 2016 at 6:20 PM

    no one in our class taught me like this,
    Its simply awesome…. just now started my course,
    only by using your website only,
    i planned to go through daily,
    please help me for queries,

    Reply
  22. Luke says

    June 18, 2016 at 1:50 PM

    Very nice and uncomplicated way of explaining! Good job!!

    Reply
  23. Pankaj says

    June 20, 2016 at 2:52 PM

    your case 4 is not valid,

    float mymethod(int a, float b)
    float mymethod(float var1, int var2)

    when we call them with values, it will throw an error like error: reference to print is ambiguous h.print(10, 20);
    cause both are taking int value, that’s why reference variable is getting confused while selecting/calling them,

    Reply
  24. Kd says

    July 6, 2016 at 7:29 PM

    Excellent notes on method overloading! Kudos!

    Reply
  25. pooja says

    September 12, 2016 at 3:21 PM

    The concepts are clear and easy to understand. thank you

    Reply
  26. venkat says

    October 2, 2016 at 10:01 PM

    F:javaprograms>javac TestOverloading3.java
    F:javaprograms>java TestOverloading3
    Error: Could not find or load main class TestOverloading3
    its compiling successfully ,but its showing error like this while run.
    may i know why i am getting like this error

    Reply
  27. Shiva says

    November 13, 2016 at 7:07 PM

    Method Overloading Concepts are very clearly understood and got registered in my mind. Thanks a lot.

    Reply
  28. Deepanshu Jain says

    November 23, 2016 at 10:13 AM

    Just wanted to add one more case :
    If just return type is different !!

    public double myMethod(int num1, int num2)
    {
    System.out.println(“First myMethod of class Demo”);
    return num1+num2;
    }
    public float myMethod(int var1, int var2)
    {
    System.out.println(“Second myMethod of class Demo”);
    return var1-var2;
    }

    throw an error.

    Reply
    • Rakesh Ranjan says

      February 6, 2017 at 11:33 AM

      Already there in Question 2

      Reply
  29. Rajneesh Kaundal says

    January 12, 2017 at 1:04 PM

    Explained very well, Anyone can understand :)

    Reply
  30. EDISON MUALA says

    April 1, 2017 at 9:38 AM

    Thank you so much.the notes are clear and easy to follow.please keep up doing the good job, you have assisted me so much

    Reply
  31. sanad alteggaz says

    June 28, 2017 at 11:41 PM

    System.out.println(” thank you pro !!!”);

    Reply
  32. Himanshu Yadav says

    July 12, 2017 at 5:59 AM

    Can we take input at compile time in case of method overloading •••••?With the help of keyboard???

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap