News for hackers. Stuff that matters.
Re:Java is Pass-by-Value, Dammit by barrkel on Sunday March 22, 2015 @09:28PM (#9249014)
Java objects are not value types; they're reference types. You're confusing your concepts. Specifically, you're conflating parameter passing semantics with reference type semantics. The problem with this conflation is that reference type semantics cover more situations than merely parameter passing, so when you conflate the two concepts, you miss out on the remaining bits. Consider this:

    Foo x = new Foo();
    x.setBar(42);
    Foo y = x;
    y.setBar(0);
    assert(x.getBar() == 42); // fails! astonishing behaviour!
If the value of x was assigned to y, surely modifying y shouldn't affect x, right? That's what assignment does, it takes the value on the right and puts it in the location on the left, correct? So why on earth was x modified when we only called a mutator method on y?

To understand this, you need to know that Java objects are reference types. And this has nothing to do with parameter passing.

And once you understand reference type semantics, you don't need anything extra to understand parameter passing, because parameter passing in Java uses the same semantics as assignment: that is, the value of the actual parameter is copied into the formal parameter, just like values on the right of an assignment are copied into the locations on the left. It's pass by copy.

There are no comments on this comment yet.