What is a Method:
A method is a block of code that performs a specific task. The code inside the method executes only when the method is called.
Syntax:
returnType methodName(parameters) {
// code
}
Example:
public class Demo {
void greet() {
System.out.println("Hello Bala");
}
public static void main(String[] args) {
Demo obj = new Demo();
obj.greet();
}
}
Output:
Hello Bala
Why Use Methods?
Code Reusability
Reduces Code Duplication
Easy Maintenance
Better Readability
What is Method Overloading:
Method Overloading means creating multiple methods with the same name in the same class but with different parameters.
The parameters can differ by:
Number of parameters.
Type of parameters.
Order of parameters.
Example:
public class CalculatorOverloading {
void add(int a, int b) {
System.out.println(a + b);
}
void add(int a, int b, int c) {
System.out.println(a + b + c);
}
public static void main(String[] args) {
CalculatorOverloading obj =
new CalculatorOverloading();
obj.add(10, 20);
obj.add(10, 20, 30);
}
}
Output:
30
60
How It Works?
obj.add(10,20)
↓
Compiler calls:
add(int,int)
obj.add(10,20,30)
↓
Compiler calls:
add(int,int,int)
Why Use Method Overloading?
It allows us to use the same method name for performing similar operations.
It improves code readability and makes the program easier to understand.
It helps achieve Compile-Time Polymorphism in Java.