7-Passing and Returning Objects from Methods in Java

Introduction

🧠 Fundamental Concept: How Java Passes Arguments

Java is strictly pass-by-value.

But here is the important part:

  • For primitive types β†’ value is copied
  • For objects β†’ reference value is copied

πŸ“Œ That means:
When passing an object to a method, Java copies the reference, not the object itself.

This distinction is extremely important πŸ”‘


🟒 Part 1: Passing Primitive Data (For Comparison)

Let’s first understand primitives.


▢️ Example 1: Passing Primitive Variable

class Test {

    void changeValue(int x) {
        x = 50;
    }
}

public class PrimitiveDemo {
    public static void main(String[] args) {

        int a = 10;

        Test t = new Test();
        t.changeValue(a);

        System.out.println(a);
    }
}

πŸ–¨ Output

10

🧠 Explanation

  • a is 10
  • Method receives a copy of a
  • x = 50 changes only the copy
  • Original a remains unchanged

Primitive values are fully copied.


🟒 Part 2: Passing Objects to Methods

Now let’s see what happens with objects.


▢️ Example 2: Passing Object to Method

class Student {
    int rollNo;

    void changeRoll(Student s) {
        s.rollNo = 200;
    }
}

public class ObjectPassingDemo {
    public static void main(String[] args) {

        Student s1 = new Student();
        s1.rollNo = 100;

        s1.changeRoll(s1);

        System.out.println(s1.rollNo);
    }
}

πŸ–¨ Output

200

🧠 Step-by-Step Explanation

1️⃣ s1 object created in heap
2️⃣ s1.rollNo = 100
3️⃣ changeRoll(s1) is called
4️⃣ Copy of reference is passed
5️⃣ Both references point to same object
6️⃣ s.rollNo = 200 modifies the object

πŸ“Œ Since both references point to the same object, the change is visible outside.


🧠 Important Concept: Reference Copy

When passing object:

  • Object itself is NOT copied
  • Reference is copied
  • Both references point to same memory

🟒 Part 3: Reassigning Reference Inside Method

Now consider this tricky case.


▢️ Example 3: Reassigning Object Inside Method

class Student {
    int rollNo;

    void changeObject(Student s) {
        s = new Student();
        s.rollNo = 500;
    }
}

public class ObjectReassignDemo {
    public static void main(String[] args) {

        Student s1 = new Student();
        s1.rollNo = 100;

        s1.changeObject(s1);

        System.out.println(s1.rollNo);
    }
}

πŸ–¨ Output

100

🧠 Why Did It Not Change?

Inside method:

  • s is a copy of reference
  • s = new Student() makes it point to new object
  • Original s1 is unaffected

πŸ“Œ Reassigning reference does NOT affect original reference.


🟒 Part 4: Returning Objects from Methods

Methods can return objects just like primitive values.


▢️ Example 4: Returning a New Object

class Number {
    int value;

    Number(int v) {
        value = v;
    }

    Number increment() {
        return new Number(value + 1);
    }
}

public class ReturnObjectDemo {
    public static void main(String[] args) {

        Number n1 = new Number(10);
        Number n2 = n1.increment();

        System.out.println(n1.value);
        System.out.println(n2.value);
    }
}

πŸ–¨ Output

10
11

🧠 Explanation

  • increment() creates new object
  • Returns new object reference
  • Original object remains unchanged

This approach promotes immutability πŸ”’


🟒 Part 5: Returning Current Object (this)


▢️ Example 5: Returning this

class Sample {
    int x;

    Sample setValue(int x) {
        this.x = x;
        return this;
    }
}

public class ReturnThisDemo {
    public static void main(String[] args) {

        Sample s = new Sample();
        s.setValue(20);

        System.out.println(s.x);
    }
}

πŸ“Œ Returning this enables method chaining.


🟒 Part 6: Passing Object and Modifying State


▢️ Example 6: Bank Account Example

class BankAccount {
    double balance;

    void deposit(double amount) {
        balance += amount;
    }
}

public class BankDemo {
    public static void main(String[] args) {

        BankAccount acc = new BankAccount();
        acc.balance = 1000;

        acc.deposit(500);

        System.out.println(acc.balance);
    }
}

πŸ–¨ Output

1500.0

Object state changes because reference points to same object.


⚠️ Common Confusions

❓ Is Java pass-by-reference?

❌ No
βœ” Java is pass-by-value (reference value copied)


❓ Why object changes but primitive doesn’t?

Because object reference points to same object.


❓ Can object be cloned automatically?

❌ No
Must explicitly clone.


❌ Common Mistakes

❌ Assuming object is fully copied

Student s2 = s1;

Both refer to same object.


❌ Reassigning inside method expecting change

s = new Student();

Does not affect original reference.


❌ Forgetting null checks

void show(Student s) {
    System.out.println(s.rollNo); // NullPointerException possible
}

πŸ§ͺ Tricky Example (Very Important)

class Test {
    int x = 10;

    void modify(Test t) {
        t.x = 50;
        t = new Test();
        t.x = 100;
    }
}

public class TrickyDemo {
    public static void main(String[] args) {

        Test t1 = new Test();
        t1.modify(t1);

        System.out.println(t1.x);
    }
}

πŸ–¨ Output

50

🧠 Why?

  • t.x = 50 modifies original object
  • t = new Test() changes only local reference
  • Original object remains 50

πŸ“Œ Key Takeaways

  • Java is pass-by-value
  • Object reference value is copied
  • Modifying object state affects original
  • Reassigning reference does not affect original
  • Returning objects creates flexibility
  • Returning this enables chaining

βœ… Conclusion

Passing and returning objects from methods is one of the most important concepts in Java OOP πŸš€

By clearly understanding:

  • How references work
  • How Java passes arguments
  • What gets copied
  • When objects change
  • When they do not change

Java programming becomes predictable, logical, and much easier to reason about πŸ’ͺ

Mastering this concept lays the foundation for:

  • Method chaining
  • Immutable design
  • Advanced OOP design
  • Real-world application architecture

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *