File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Difference between passing by a reference and passing a new object?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Difference between passing by a reference and passing a new object??" Watch "Difference between passing by a reference and passing a new object??" New topic
Author

Difference between passing by a reference and passing a new object??

Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1277

what would be the difference between below statements

Employee e = new Employee();

myMethod(e); // statement 1
myMethod(new Employee) //statement 2

Thanks


No Kaustubh No Fun, Know Kaustubh Know Fun..
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10486
    
    9

What do you think?


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1277

I am not sure but one of my friend told me, that whatever values change does by the method is reflect in first but not in second... I tried that but I was getting same values in both case.
Ahsan Bagwan
Ranch Hand

Joined: Oct 05, 2010
Posts: 161
Which values are you referring to? If you mean `e` then it is just a reference. It will only affect the member variables of the object it references if you alter it in the method.

Otherwise `e` is just a copy of the reference and passed in by value. So only the fields of the object changes, I think.

Taken from the last section here

Though I may be wrong.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10486
    
    9

What value changes? How is it related to what you originally asked?
Difference between passing by a reference and passing a new object??
Kaustubh G Sharma
Ranch Hand

Joined: May 13, 2010
Posts: 1277

Yeah that I understand, but is there any difference In their execution?
Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 679
Kaustubh G Sharma wrote:Yeah that I understand, but is there any difference In their execution?

No. The only difference between those two statements is that with the second one there will be no reference to the object in the calling code. As soon as the method returns (assuming no new references to it were created in the method) the object will be eligible for garbage collection, whereas in the first one it won't because 'e' is still referencing it.
 
jQuery in Action, 2nd edition
 
subject: Difference between passing by a reference and passing a new object??