Java Reference
In-Depth Information
model
Unknown
year
2000
myCar
8192
5120
5120
price
0.0
model
Civic LX
year
1999
9216
xyCar
10240
9216
price
16000.0
Figure 6-19.
Memory state of reference variables myCar and xyCar and two Car objects
Let's make one more change and set the
xyCar
reference variable to
null
as shown:
xyCar = null; /* #6 */
Figure
6-20
shows the memory state after statement #6 is executed.
model
Unk nown
year
2000
5120
myCar
8192
5120
price
0.0
model
Civ ic LX
year
1999
9216
xyCar
10240
null
price
160 00. 0
Figure 6-20.
Memory state of reference variables myCar and xyCar and two Car objects after xyCar has been assigned
a null reference
Now the
xyCar
reference variable stores a
null
reference and it no longer refers to any
Car
object. The
Car
object
with
Civic LX
model is not being referenced by any reference variable. You cannot access this
Car
object at all in your
program because you do not have a reference to it. In Java terminology, the
Car
object with the
Civic LX
model is
not reachable. When an object in memory is not reachable, it becomes eligible for garbage collection. Note that the
Car
object with the
Civic LX
model is not destroyed (or deallocated) immediately after
xyCar
is set to
null
. It stays in
memory until the garbage collector runs and makes sure that it is not reachable. Please refer to the chapter on garbage
collection for more details on how an object's memory is deallocated.
I have covered enough background about variables types and how they work in Java. It is time to discuss the
parameter passing mechanism in Java. In brief, we can state
All parameters in Java are passed by value.