Question

i went through several post in stackoverflow and googled other good sites to understand the concepts of java pass by value..

my doubt goes as below.

Dog someDog = new Dog("FOO"); //mem location 42
foo(someDog);
someDog.setName("FIFI"); // false

    foo(Dog newDog){
      newDog.name.equals("FOO"); //true
      newDog = new Dog("FIFI");  // create a new DOG object mem location 72. my doubt here
      newDog.name.equals("FIFI"); //true
    }

so as above in the line newDog = new Dog("FIFI"); my understanding goes new DOG object is created at mem location 72 and assigned to another Dog location object at mem location 42.

what does it means? at the background..

Regards Punith.

Was it helpful?

Solution 2

void foo(Dog newDog){
    newDog.name.equals("FOO"); //true
    newDog = new Dog("FIFI");  // create a new DOG object mem location 72. my doubt here
    newDog.name.equals("FIFI"); //true
}

Here newDog is a local variable to that method. When you call that method and pass someDog, the value of someDog (which is a reference to a Dog object) is copied into newDog. So now you have 2 references pointing to the same object. That's why the first line evaluates to true.

After you execute

newDog = new Dog("FIFI");

the variable newDog references the newly created Dog object. This does not change the variable someDog at all. So now, you have 2 variables, each pointing to a different Dog object.

After the method is done, the newDog variable disappears, and the newly created Dog object has no more reference pointing to it, so it becomes eligible for garbage collection.

The code posted in the method doesnt't change any attributes of the object referenced by someDog, and it can never switch the object referenced by someDog

That's why

someDog.setName("FIFI"); // is false

Understood?

OTHER TIPS

One picture is worth thousand words, so here is what is going on:

Variable to object diagrams

As you can see, the two variables someDog in the caller and newDog in the foo reference the same object initially. After the assignment, they reference different objects, explaining the behavior that you see: since Dog is passed by reference, and because you created a new Dog rather than modifying the existing one, newDog becomes unrelated to someDog after the assignment.

Note that if you modified the existing dog, the picture would have been different: if you did newDog.setName("FIFI"); inside foo, rather than newDog = new Dog("FIFI");, the results would be different: the diagram would still look like the middle picture, but the dog's name would have been FIFI.

You are creating a new Dog object (FIFI) and letting the method parameter newDog reference this new object. This has no effect whatsoever on the object still referenced by someDog. So, this variable does still reference the same object. Was this what you are wondering about?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top