Passing Primitive Data Types to Methods
1. Rule in One Line (beginner)
Primitives pass by value (photocopy!). Method gets a copy — changes die with method. Original NEVER changes!
2. Proof Code (exam trace!)
static void addOne(int x) { x = x + 1; } // edits COPY!
public static void main(String[] args) {
int n = 10;
addOne(n);
System.out.println(n); // still 10! (original untouched!)
}
Swap fails too:
static void swap(int a, int b) { int t = a; a = b; b = t; } // copies swap, originals don't!
int x = 1, y = 2; swap(x, y); // x=1,y=2 still! (classic trap!)
main: n=10 → copy x=10 → x=11 (method) → die! → n still 10
Objects/arrays differ (address copy — shared! next topics!).
5. Exam Points
- Trace (
nunchanged) + failed swap — 5-7 marks, very frequent. - By-value diagram + fix — 3 marks, frequent.