Question

In the following image, p points to person.

p is passed as a reference to a function named callFunction. Now,if I make any change in p will they also get reflected in person ? Please explain.

I understand that argument passed is the reference value of the original variable (I hope so !). But I can't think further.

enter image description here

Was it helpful?

Solution

If you change the details of p as such, it'll get reflected

// Nothing done to p before this
p.changeName("Not Sanika Anymore"); // This will be reflected as both point to the same object as references are the same

If you create a new Person and assign it to p then it wont

// New Person for p
p = new Person("New Sanika"); // now this p is pointing to the newly created object's reference
p.changeName("Not Sanika Anymore"); // This won't be reflected

That is because java is purely pass-by-value. You are passing the reference of the object as a value to callFunction().

This answer by Eng.Fouad explains this concept in a really good way.

OTHER TIPS

Yes, because both reference are pointing to same Person object. When you change some attribute using any reference, same object will be updated.

As long as you change the members of the object which is pointed by the reference p , They'll get reflected , As java passes parameter by value .

What is Pass by value ??

The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter's value during method/function execution. That location is typically a chunk of memory on the run-time stack for the application (which is how Java handles it), but other languages could choose parameter storage differently. So there is no way of the method having contact with the original reference here.

So Pass by reference is implemented differently , this is where actually you can have freedom of playing with reference . Here references can be changed in the method .

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