Methods of Java · Introduction to Java Programming

Passing Objects to Methods

Watch lectures

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.
Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.

← All Introduction to Java Programming modules