So I was reading this post and response no. 2. In that example, after calling that method, does the Dog value at address 42, name’s changes to Max?
Dog myDog;
Dog myDog = new Dog("Rover");
foo(myDog);
public void foo(Dog someDog) {
someDog.setName("Max"); // AAA
someDog = new Dog("Fifi"); // BBB
someDog.setName("Rowlf"); // CCC
}
Java is pass by value – always, both for primitives and objects.
In the case of objects, the thing that’s passed is the reference to the object that lives out on the heap. A method cannot change what that reference points to when it’s passed in.
If that reference points to an object that has mutable data, the method can alter its state.
From “The Java Programming Language Second Edition”, by Ken Arnold and James Gosling (ISBN 0-201-31006-6 ) (probably from page 40–don’t have the book handy right now):
So let’s look at your example (with some improvements):
Here’s the output:
You can’t change what the reference that’s passed to
foopoints to, so setting it to the reference with the name “Fifi” at line BBB, and subsequently changing the name of that object at line CCC, does nothing. That instance is eligible for garbage collection whenfooexits.The incoming reference that points to “Rover” has a mutable data member: its name. Changing its value at line AAA is reflected in the reference that was passed in; hence the different output.