What is the difference between the first code snippet and the second? Why do you think that difference changes the result?
First snippet
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog;
// we pass the object to foo foo(aDog);
// aDog variable is still pointing to the "Max" dog when foo(...)
returns aDog.getName().equals("Max"); // true
aDog.getName().equals("Fifi"); // false
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true
}
Second snippt
public static void main(String[] args) {
Dog aDog = new Dog("Max");
Dog oldDog = aDog; foo(aDog); // when foo(...) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog:
aDog == oldDog; // true
}
public static void foo(Dog d) {
d.getName().equals("Max"); // true // this changes the name of d to be "Fifi"
d.setName("Fifi");
}
What is the difference between the first code snippet and the second?
Why do you think that difference changes the result?
Step by step
Solved in 2 steps