How does the Java compiler determine which overloaded method to call?

When an overloaded method is called, the Java compiler determines which version to execute by examining the method name, the number of arguments, the data types of the arguments, and their order. The compiler selects the most specific method that best matches the provided arguments. Since this decision is made during compilation, method overloading is known as compile-time polymorphism.

Key Points: • The compiler matches methods based on the method signature (name + parameter list). • It considers the number, type, and order of arguments. • The most specific matching method is selected. • Method overloading is resolved at compile time, not runtime. • If no suitable method is found, a compilation error occurs.

Example: A Calculator class may contain multiple versions of the add() method. Depending on the arguments passed, the compiler chooses the appropriate method.

Code Example:

class Calculator {

    void add(int a, int b) {
        System.out.println("int version");
    }

    void add(double a, double b) {
        System.out.println("double version");
    }

    void add(int a, int b, int c) {
        System.out.println("three-parameter version");
    }
}

public class Demo {

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        calculator.add(10, 20);

        calculator.add(10.5, 20.5);

        calculator.add(10, 20, 30);
    }
}

Output:

int version double version three-parameter version

How the Compiler Chooses a Method:

1. Exact Match

calculator.add(10, 20);

The compiler finds add(int, int) and selects it.

2. Type Match

calculator.add(10.5, 20.5);

The compiler finds add(double, double).

3. Parameter Count Match

calculator.add(10, 20, 30);

The compiler selects add(int, int, int).

Method Resolution Priority:

The compiler generally follows this order:

• Exact Match • Primitive Type Promotion • Autoboxing • Varargs

Example:

void display(int num) { }

void display(long num) { }

display(10);

The compiler chooses display(int) because it is an exact match.

Benefits:

• Improves code readability • Allows the same method name for related operations • Reduces unnecessary method names • Provides compile-time flexibility

Interview Tip: A concise interview answer is:

"The Java compiler resolves overloaded methods at compile time by checking the number, type, and order of arguments. It selects the most specific method that best matches the provided arguments, making method overloading an example of compile-time polymorphism."