Understanding Methods
1. Why Methods? (beginner)
Method = named reusable work-block (verb!). Avoids copy-paste: write add() once, call 100×. Makes code readable, testable, DRY (Don't Repeat Yourself!).
2. Call Flow (stack!)
public class M {
static int add(int a, int b) { return a + b; } // definition
public static void main(String[] args) {
int s = add(3, 4); // CALL (jump + args 3,4 → a,b!)
System.out.println(s); // 7
System.out.println(add(10, 20)); // direct use!
}
}
Steps: main frame pauses → add frame (a=3,b=4) → returns 7 → main resumes. Args copy by value (primitives!).
3. Method Kinds (preview map!)
| Kind | Call style | Example |
|---|---|---|
| static | ClassName.m() (no object!) |
Math.sqrt(16) |
| instance | obj.m() (needs object!) |
s.length() |
| void vs return | statement vs value | print() vs add() |
4. Beginner Rules
- Define inside class (never inside another method!).
- Call
staticfromstaticdirectly; instance needs object (else ERROR!). - Same name + different params = overloading (legal!).
5. Exam Points
- Define + call-trace with stack — 5 marks, very frequent.
- Static vs instance call — 3 marks, frequent.