0
0
Javaprogramming~15 mins

Method overloading in Java

Choose your learning style8 modes available
menu_bookIntroduction

Method overloading lets you create multiple methods with the same name but different inputs. This helps keep your code neat and easy to understand.

When you want to perform similar actions but with different types or numbers of inputs.
When you want to simplify method names instead of creating many different names for similar tasks.
When you want to improve code readability by grouping related operations under one method name.
When you want to provide flexible ways to call a method depending on available data.
regular_expressionSyntax
Java
returnType methodName(type1 param1) {
    // method body
}

returnType methodName(type1 param1, type2 param2) {
    // method body
}

returnType methodName(type1 param1, type2 param2, type3 param3) {
    // method body
}

All methods share the same name but differ in parameter types or number.

Return type alone cannot distinguish overloaded methods.

emoji_objectsExamples
line_end_arrow_notchTwo methods named add: one adds two numbers, the other adds three.
Java
int add(int a, int b) {
    return a + b;
}

int add(int a, int b, int c) {
    return a + b + c;
}
line_end_arrow_notchTwo print methods: one prints text, the other prints a number.
Java
void print(String message) {
    System.out.println(message);
}

void print(int number) {
    System.out.println(number);
}
code_blocksSample Program

This program shows two greet methods. One says hello with a name. The other adds the person's age.

Java
public class OverloadExample {
    // Method to greet with a name
    void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    // Overloaded method to greet with name and age
    void greet(String name, int age) {
        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }

    public static void main(String[] args) {
        OverloadExample example = new OverloadExample();
        example.greet("Alice");
        example.greet("Bob", 30);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Method overloading is decided at compile time based on method signatures.

line_end_arrow_notch

Changing only the return type does not create an overloaded method.

line_end_arrow_notch

Use overloading to make your code easier to read and maintain.

list_alt_checkSummary

Method overloading means having methods with the same name but different parameters.

It helps write cleaner and more flexible code.

Java chooses which method to run based on the inputs you give.