Java Reference
In-Depth Information
System.out.println("before: one = " + one);
halveIt(one);
System.out.println("after: one = " + one);
}
public static void halveIt(double arg) {
arg /= 2.0; // divide arg by two
System.out.println("halved: arg = " + arg);
}
}
The following output illustrates that the value of
arg
inside
halveIt
is di-
vided by two without affecting the value of the variable
one
in
main
:
before: one = 1.0
halved: arg = 0.5
after: one = 1.0
You should note that when the parameter is an object reference, it is
the object
reference
not the object itselfthat is passed "by value." Thus,
you can change which object a parameter refers to inside the method
without affecting the reference that was passed. But if you change any
fields of the object or invoke methods that change the object's state, the
object is changed for every part of the program that holds a reference
to it. Here is an example to show this distinction:
class PassRef {
public static void main(String[] args) {
Body sirius = new Body("Sirius", null);
System.out.println("before: " + sirius);
commonName(sirius);
System.out.println("after: " + sirius);
}