| Author |
Passing Object to a method
|
Randy Gavri
Greenhorn
Joined: Oct 23, 2008
Posts: 2
|
|
Here is a sample code and the corresponding output which baffles me. ----------------------------------- ----------------------------------------------------- The output : before changing attribute >10 after changing attribute >20 after setting the object to null>20 -------------------------------------- How is that when we pass an object to a method and change its attribute's value in the caliing method it gets reflected in the main method but if we change the object itself in the calling method it does not get reflected in the main method After callin the changeObject method the next line is trying to access its attribute of a null refrence. It shud give a nullpointerexception right?? Can any one please explain the concept behind the behaviour. [ October 23, 2008: Message edited by: Randy Gavri ] [ October 23, 2008: Message edited by: Randy Gavri ] [edit]Add code tags. CR[/edit] [ October 23, 2008: Message edited by: Campbell Ritchie ]
|
 |
Vijitha Kumara
Bartender
Joined: Mar 24, 2008
Posts: 3670
|
|
Actually you are not passing the object here. When you call a method with a object reference you passes a copy of the reference (i.e: that method has it's local reference to the object). When you make it null you are loosing the local reference. But the original reference exists. [ October 23, 2008: Message edited by: Vijitha Kumara ]
|
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
|
 |
Ridhav Mahajan
Greenhorn
Joined: Oct 23, 2008
Posts: 11
|
|
Actually in java there is nothing as "call by reference". Everything n java is call by value, In case of normal primitive types,they behave as normal call by value passing, but when we pass objects as parameters, we pass the memory address of that object as call by value, o if you change that memory address it ill not be reflected in the calling function. But if you change some attributes in that object, they are actually changed at the original location because we have the address of actual variables of that object. Now in this case you are changing the memory addres to null, which is passed as call by value.
|
Ridhav
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32688
|
|
Welcome to JavaRanch Please note we have a feature (the CODE button) which preserves indentation. I have edited your post so you can see how much better it looks. Do a search of the Ranch for "pass by value pass by reference" and you will find several old threads which give useful information about this question. Threads like this, this, and this, as well as this JavaRanch article. Some of those old threads contain a link to pass-by-value and pass-by-reference in Pascal, which makes interesting reading.
|
 |
Randy Gavri
Greenhorn
Joined: Oct 23, 2008
Posts: 2
|
|
|
Thanks Campbell.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32688
|
|
You're welcome
|
 |
 |
|
|
subject: Passing Object to a method
|
|
|