Java.Core.How does Java implement pass-by-value?

📦 What gets passed?

TypeWhat gets passed?
Primitives (int, double, boolean, etc.)The actual value (a copy of the primitive itself)
Objects (String, List, etc.)A copy of the reference to the object (not the object itself)

🔥 What does this mean practically?

✅ Example 1 — Primitives

public class PassByValueDemo {
    public static void main(String[] args) {
        int number = 5;
        changePrimitive(number);
        System.out.println(number);  // Still 5 (original unaffected)
    }

    static void changePrimitive(int num) {
        num = 10;  // This only changes the local copy
    }
}

number is passed by value, meaning a copy of 5 is passed into changePrimitive.The num variable inside changePrimitive is independent of the original number.

✅ Example 2 — Objects (The Confusing Part)

public class PassByValueDemo {
    static class Person {
        String name;
        Person(String name) {
            this.name = name;
        }
    }

    public static void main(String[] args) {
        Person person = new Person("Alice");
        changePerson(person);
        System.out.println(person.name);  // Bob
    }

    static void changePerson(Person p) {
        p.name = "Bob";  // This changes the actual object's field
    }
}
  • person is passed by value, meaning a copy of the reference is passed to changePerson.
  • Both person (in main()) and p (in changePerson()) point to the same object.
  • So modifying fields inside the object works.

❌ What doesn’t work (Reassigning the reference itself)

static void changePerson(Person p) {
    p = new Person("Charlie");  // This only changes the local copy of the reference
}

This doesn’t affect the original person in main(), because the reference itself is passed by value.Only p now points to Charlie, but person in main() still points to Alice.

✅ Rule to Remember

TypeWhat gets passed?Can you change the original?
PrimitiveCopy of value❌ No
Object ReferenceCopy of reference✅ Yes, if you modify the object’s internal state (fields)
Object ReferenceCopy of reference❌ No, if you reassign the reference itself

📊 Quick Analogy

Think of it like giving someone a copy of your house key.

  • They can use the key to change things inside the house (furniture, painting the walls) — this is modifying fields inside the object.
  • But if they throw away the key and create a new house, your original house is unaffected — this is reassigning the reference.

⚠️ Important Misconception

Java is pass-by-reference for objects. (This is wrong!)
Java is always pass-by-value — but what gets passed is a copy of the reference, not the object itself.


📚 Summary

ConceptPrimitivesObjects
Passed asCopy of valueCopy of reference
Changing the object itselfN/AAffects original object
Reassigning the parameterNo effect on originalNo effect on original
This entry was posted in Без рубрики. Bookmark the permalink.