Passing Objects to Methods
1. Rule (beginner — different from primitives!)
Objects pass address-copy (house remote photocopied — SAME house!). Method CAN change object's fields (shared!). But reassigning the remote (obj = new...) doesn't affect caller!
class Box { int x; }
static void change(Box b) { b.x = 99; } // edits SHARED house!
static void replace(Box b) { b = new Box(); b.x = 1; } // new house (caller unaffected!)
public static void main(String[] args) {
Box o = new Box(); o.x = 10;
change(o); System.out.println(o.x); // 99 (changed! shared!)
replace(o); System.out.println(o.x); // still 99 (reassign died!)
}
4. String Twist (immutable!)
String is object BUT immutable: s = s + "!"; inside method reassigns local (caller unchanged!). Like primitive!
5. Exam Points
- Field-change vs reassign trace — 7 marks, very frequent.
- Primitives vs objects table — 5 marks, frequent.