Intermediate
Method Overloading and Variable Scope
📂 Phase 2: Control Flow & Data (Days 6–10) · JavaMethod overloading lets you define multiple methods with the same name but different parameter lists — Java decides which version to call based on the arguments you pass.
Method Overloading Example
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public 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)); // calls version 1 → 5
System.out.println(add(2.5, 3.5)); // calls version 2 → 6.0
System.out.println(add(1, 2, 3)); // calls version 3 → 6
}
Rules for Valid Overloading
- Methods must differ in the number of parameters, OR
- Methods must differ in the type of parameters, OR
- Methods must differ in the order of parameter types
Changing only the return type is NOT enough to overload a method — int add(int a, int b) and double add(int a, int b) with identical parameters will not compile.
Variable Scope
Scope determines where in your code a variable can be accessed. Java has three main scope levels:
| Scope | Where Declared | Accessible From |
|---|---|---|
| Local | Inside a method or block | Only within that method/block |
| Instance | Inside a class, outside any method | Any non-static method in that object |
| Class (static) | Inside a class with the static keyword | Shared across all objects of the class |
Local Scope Example
public static void method1() {
int x = 10; // local to method1
System.out.println(x);
}
public static void method2() {
System.out.println(x); // ERROR — x doesn't exist here
}
Block Scope Inside Loops
for (int i = 0; i < 5; i++) {
int square = i * i; // square only exists inside this loop body
}
// System.out.println(square); // ERROR — square is out of scope here
Interview tip: A favorite trick question is asking what happens if you declare a local variable with the same name as an instance variable — the local variable "shadows" the instance variable within that method, and you'd need this.variableName to access the instance version.