A method is a block of code designed to perform a specific task. Methods are executed only when they are called, making programs more structured, reusable, and easier to maintain.
What is a Method?
A method is similar to a function in other programming languages. It groups a set of statements together to perform an operation.
class Test {
static void greet() {
System.out.println("Hello, Java!");
}
public static void main(String[] args) {
greet(); // method call
}
}
Execution Flow
- The program starts from the main() method
- greet() method is called
- The message is printed
Method Overloading
Method Overloading is a feature in Java where multiple methods share the same name but differ in their parameters. It is an example of compile-time polymorphism.
Method overloading means:
- Same method name
- Different parameter list (type, number, or order)
Different Number of Parameters
class Test {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // 2 params
System.out.println(add(2, 3, 4)); // 3 params
}
}
Different Data Types
class Test {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(5, 10)); // int
System.out.println(add(5.5, 2.5)); // double
}
}
Different Order of Parameters
class Test {
static void display(int a, String b) {
System.out.println(a + " " + b);
}
static void display(String b, int a) {
System.out.println(b + " " + a);
}
}
Important Rules
✔ Must Change Parameter List
Overloading works only if parameters differ in:
- Number
- Data type
- Order
Same name + same parameters + different return → ERROR
int add(int a, int b) { return a + b; }
// Error (same parameters)
double add(int a, int b) { return a + b; }
Why Use Method Overloading?
- Improves code readability
- Reduces method name complexity
- Reuse same method name for similar operations
Example
System.out.println(10);
System.out.println("Hello");
System.out.println(3.14);
println() is overloaded to handle different data types.
At compile time, Java decides:
- Which method to call based on arguments
- This is called compile-time polymorphism
Summary
- Same method name
- Different parameters
- Compile-time decision
- Improves flexibility and readability