Method Overloading in Java with Example Program

In this tutorial, we will be going to discuss on the topic Method Overloading in Java. Further, we will be looking more on what Methods are and how it gets overloaded.

If you don’t know about the topic Methods overloading in java then you are at the right place because we will be discussing the topic deeply.

Method Overloading is a feature provided by java which allows multiple methods to have the same name if their arguments are different.

Different Ways To Overload Methods in Java

There are multiple ways to overload a method. Two of them are :

  1. By Changing the DataType.
  2. By Changing the No. of Arguments.

1. By Changing the DataType: In this example, ‘output’ method is overloaded based on the different data type of parameters – We have two methods with the name, one with a parameter of character datatype and another method with the parameter of integer datatype. We are Passing different types of values in the above methods. Similarly, we can change the datatypes as required. We can change the datatypes as we want to change or pass to the methods.

class CheckOverLoad
    public void output(char d)
    public void output(int d)

class chk1
    public static void main(String args[])
        CheckOverLoad obj1 = new CheckOverLoad();

2. By Changing The No. of Arguments: Below is an example of No. OF arguments changed while passing to the methods. In this example, we are providing the ‘Add’ method with different no. of parameters. In the first ‘Add’ method, we are passing two values and we get the result of the addition of two variables whereas in the next ‘Add’ method we passed three values and it returned the Addition of 3 values and hence we Produce desired output. Similarly, we can pass different no. of values to a Method in Java.

class Addition{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}  
class chk2{  
public static void main(String[] args){  

Below is the output of the above two examples demonstrating the different results for the above codes.

Method Overloading in Java

By this, We can overload a method in a different approach in java.

You may also read:

Leave a Reply

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