DEV Community

Cover image for Method Overloading in Java
Harini
Harini

Posted on

Method Overloading in Java

Method Overloading is a feature in Java where multiple methods have the same name but different parameters.

It helps improve code readability and allows you to use the same method name for different tasks.

Rules for Method Overloading
To overload a method, you must change at least one of the following:

  1. Number of parameters
  2. Type of parameters
  3. Order of parameters
  • Changing only the return type is NOT allowed

Example 1: Different Number of Parameters

class Calci {

    public static void main(String[] args) {
        Calci obj = new Calci();

        System.out.println(obj.add(10, 20));      
        System.out.println(obj.add(10, 20, 30));  
    }

    int add(int a, int b) {
        System.out.println("2 arguments");
        return a + b;
    }

    int add(int a, int b, int c) {
        System.out.println("2 arguments");
        return a + b + c;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Example 2: Different Data Types

class Student {


    public static void main(String[] args) {
        Student obj = new Student();

        obj.show(100);
        obj.show("Harini");
    }

    void show(int a) {
        System.out.println("Integer: " + a);
    }

    void show(String a) {
        System.out.println("String: " + a);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Example 3: Order of Parameters

class Test {

    public static void main(String[] args) {
        Test obj = new Test();

        obj.print(10, "Java");
        obj.print("Hello", 20);
    }

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

    void print(String b, int a) {
        System.out.println(b + " " + a);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Step-by-Step Execution

  1. Program starts from main() method
  2. Object is created
  3. Method is called
  4. Java checks:
    • Number of arguments
    • Data type of arguments
  5. Matching method is executed
  6. Output is displayed

Top comments (0)