Java Reference
In-Depth Information
#1: a = 19, b = 37
#2: x = 19, y = 37
#3: x = 19, y = 223
#4: a = 19, b = 37
Let's discuss the parameter passing mechanism for reference type parameters. Java lets you use the pass by
reference value and pass by constant reference value mechanisms to pass reference type parameters to a method.
When a parameter is passed by reference value, the reference stored in the actual parameter is copied to the formal
parameter. When the method starts executing, both the actual parameter and the formal parameter refer to the same
object in memory. If the actual parameter has a
null
reference, the formal parameter will contain the
null
reference.
You can assign a reference to another object to the formal parameter inside the method's body. In this case, the formal
parameter starts referencing the new object in memory and the actual parameter still references the object it was
referencing before the method call. Listing 6-24 demonstrates the pass by reference mechanism in Java. It creates a
Car
object inside the
main()
method and stores the reference of the
Car
object in
myCar
reference variable.
// Create a Car object and assign its reference to myCar
Car myCar = new Car();
It modifies the model, year, and price of the newly created
Car
object using
myCar
reference variable.
// Change model, year and price of Car object using myCar
myCar.model = "Civic LX";
myCar.year = 1999;
myCar.price = 16000.0;
The message labeled #1 in the output shows the state of the
Car
object. The
myCar
reference variable is passed to
the
test()
method using the following call:
PassByReferenceValueTest.test(myCar);
Since the type of the formal parameter
xyCar
in the
test()
method is
Car
, which is a reference type, Java
uses the pass by reference value mechanism to pass the value of the
myCar
actual parameter to the
xyCar
formal
parameter. When the
test(myCar)
method is called, Java copies the reference of the
Car
object stored in the
myCar
reference variable to the
xyCar
reference variable. When the execution enters the
test()
method's body,
myCar
and
xyCar
reference the same object in memory. At this time, there is only one
Car
object in memory and not two. It is
very important to understand that the
test(myCar)
method call did not make a copy of the
Car
object referenced by
the
myCar
reference variable. Rather, it made a copy of the reference (memory address) of the
Car
object referenced
by the
myCar
reference variable, which is the actual parameter, and copied that reference to the
xyCar
reference
variable, which is the formal parameter. The fact that both
myCar
and
xyCar
reference the same object in memory
is indicated by the message labeled #2 in the output, which is printed using the
xyCar
formal parameter inside the
test()
method.
Now you create a new
Car
object and assign its reference to the
xyCar
formal parameter inside the
test()
method.
// Let's make xyCar refer to a new Car object
xyCar = new Car();