Method overloading in Java

Method overloading is a feature in Java that allows a class to have multiple methods with the same name, but different parameters. When a method is overloaded, the method signature is different for each version of the method, with the signature being determined by the number, type, and order of the method parameters.


Java resolves which version of the method to call based on the arguments passed to the method. During compilation, the Java compiler determines which version of the overloaded method to call based on the number and type of arguments passed to the method. If it cannot determine the correct version of the method during compilation, it will generate a compilation error.


Here's an example of method overloading in Java:

public class MathOperations {
    public int add(int x, int y) {
        return x + y;
    }
    
    public double add(double x, double y) {
        return x + y;
    }
    
    public int add(int x, int y, int z) {
        return x + y + z;
    }
}


In this example, we have a class called MathOperations that has three methods called add(). Each method has a different parameter list, and so the Java compiler will determine which version of the method to call based on the arguments passed to the method.


If we call the add() method with two integers, the compiler will choose the first version of the method. If we call it with two doubles, the compiler will choose the second version. And if we call it with three integers, the compiler will choose the third version.


Here's an example of how we might use these methods:

MathOperations math = new MathOperations();
int sum1 = math.add(3, 5);          // Calls the first version of add()
double sum2 = math.add(2.5, 4.2);   // Calls the second version of add()
int sum3 = math.add(2, 4, 6);       // Calls the third version of add()


In each case, the correct version of the add() method is called based on the arguments passed to the method.