When overwriting an existing variable, someThing of type Thing below in a method, what is the correct way to do this?
doSomething(someThing);
void doSomething(Thing thing){
//...
thing = new Thing(...); // receives warning in Eclipse
}
or
someThing = doSomething(someThing);
Thing doSomething(Thing thing){
//...
return new Thing(...);
}
Your first sample doesn’t change the variable
someThingin the caller. The assignment is only visible in thedoSomethingmethod.The second sample does change
someThingin the caller.So if you want to change
someThingin the caller, option 2 is viable, while option 1 is not.See Is Java "pass-by-reference" or "pass-by-value"? for why this works that way.
Assuming the following code, and a
Thingthat has a print method and a String member.The assignment at point
1first creates a new Thing object:Then stores a reference to that in
one:When you enter
barat point2, a new reference to the same object is created:Then line
3does the same thing as line1, i.e. create a newThingobject:then stores a reference to that new object in
two:Notice that only
twois modified. The assignment changes whattworefers to.When you return from
bar, at line4,twogoes out of scope, the “bye” Thing no longer has anything referencing it (and will eventually be garbage collected).So at point
5, as you can see,hellowill be printed – nothing ever changed the object thatonerefers to.