method overloading in java
Method overloading in Java refers to the ability to define multiple methods in a class with the same name but with different parameter lists. These methods can have different numbers or types of parameters. Method overloading allows developers to create multiple methods with the same name that perform similar tasks but with variations in input parameters.

Table of Contents
Key Points about Method Overloading:
- 1. Same Method Name: Overloaded methods have the same name within the class.
- 2. Different Parameters: Overloaded methods must have different parameter lists. This can include differences in the number, type, or order of parameters.
- 3. Return Type: The return type of the overloaded methods may or may not be the same. Overloading is not determined by the return type alone.
- 4. Compile-Time Polymorphism: Method overloading is an example of compile-time polymorphism, where the appropriate method to invoke is determined by the compiler based on the method signature.
- 5. Improves Readability and Flexibility: Method overloading improves code readability by allowing developers to use the same method name for related tasks. It also provides flexibility in method invocation, as the appropriate overloaded method is chosen based on the arguments passed.
Example of Method Overloading
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of 2 and 3: " + calc.add(2, 3));
System.out.println("Sum of 2, 3, and 4: " + calc.add(2, 3, 4));
System.out.println("Sum of 2.5 and 3.5: " + calc.add(2.5, 3.5));
}
}
In this example, the ‘Calculator’ class demonstrates method overloading with three versions of the ‘add’ method. Each version takes a different number or type of parameters, allowing the ‘add’ method to perform addition for integers and doubles with different signatures.