Java Reference
In-Depth Information
public static void commonName(Body bodyRef) {
bodyRef.name = "Dog Star";
bodyRef = null;
}
}
This program produces the following output:
before: 0 (Sirius)
after: 0 (Dog Star)
Notice that the contents of the object have been modified with a name
change, while the variable sirius still refers to the Body object even
though the method commonName changed the value of its bodyRef paramet-
er variable to null . This requires some explanation.
The following diagram shows the state of the variables just after main
invokes commonName :
At this point, the two variables sirius (in main ) and bodyRef (in commonName )
both refer to the same underlying object. When commonName changes the
field bodyRef.name , the name is changed in the underlying object that
the two variables share. When commonName changes the value of bodyRef
to null , only the value of the bodyRef variable is changed; the value of
sirius remains unchanged because the parameter bodyRef is a pass-by-
value copy of sirius . Inside the method commonName , all you are changing
is the value in the parameter variable bodyRef , just as all you changed in
halveIt was the value in the parameter variable arg . If changing bodyRef
Search WWH ::




Custom Search