Method Overloading in Java

Method overloading is a feature of Java that allows you to define multiple methods with the same name in a class, but with different parameters. Java determines which method to call based on the number, types, and order of the arguments passed at the time of calling. Method overloading is a type of compile-time (static) polymorphism, which allows a program to have more than one method with the same name.

Here's an example of method overloading in Java:

                
    public class Calculator {
      public int add(int a, int b) {
        return a + b;
      }

      public double add(double a, double b) {
        return a + b;
      }

      public int add(int a, int b, int c) {
        return a + b + c;
      }
    }
                
            

In this example, we have a Calculator class with three methods named add(). The first add() method takes two integer parameters and returns the sum of the parameters. The second add() method takes two double parameters and returns the sum of the parameters. The third add() method takes three integer parameters and returns the sum of the parameters.

When you call the add() method, Java determines which method to call based on the arguments passed at the time of calling. For example, if you call the add() method with two integer parameters like this:

                
    Calculator calculator = new Calculator();
    int sum = calculator.add(2, 3);
                
            

Java will call the first add() method that takes two integer parameters and returns the sum of the parameters. If you call the add() method with two double parameters like this:

                
    double sum = calculator.add(2.5, 3.5);
                
            

Java will call the second add() method that takes two double parameters and returns the sum of the parameters. If you call the add() method with three integer parameters like this:

                
    int sum = calculator.add(2, 3, 4);
                
            

Java will call the third add() method that takes three integer parameters and returns the sum of the parameters.

Method overloading is useful when you want to perform the same operation on different types of data. It makes the code more readable and reduces the complexity of the code.