Methods Overloading in Java

Methods Overloading

Method Overloading means multiple methods can have the same name with different parameters. In java, you can create methods with the same name but different parameters. We cannot overload by return type.

int methodName(int x)
float methodName(float x)
double methodName(double x, double y)

Methods Overloading Advantage

  • We don’t have to remember different method names that do the same thing.

Example Of Method

public class Main {

    public static void main(String[] args) {
    // Calling same method with same name but different signature.
    add(10,30); // prints The sum is 40
    add(10,20,30); // prints The sum is 60
    }

    public static void add(int num1, int num2){
        int sum = num1 + num2;
        System.out.println("The sum is "+sum);
    }

    public  static void add(int num1, int num2, int num3){
        int sum = num1 + num2 + num3;
        System.out.println("The sum is "+sum);
    }
}
Show Output
  • Here are 2 methods with the same name, i.e., add
  • They have different parameter i.e (num1, num2) and (num1, num2, num3)

We Achieve Method Overloading By

  • Changing the number of parameters.
  • Changing the data type of parameters.