Java Reference
In-Depth Information
model
Unknown
year
2000
myCar
8192
9216
9216
price
0.0
Car object
The reference variable, myCar, stores reference of Car
object
Figure 6-15. Memory states for the myCar reference variable and the new Car object when the myCar = new Car()
statement is executed
The statement labeled #3 is similar to the statement labeled #1. The memory state for the xyCar reference
variable is shown in Figure 6-16 , assuming that 10240 is the memory address for the xyCar reference variable.
xyCar
10240
null
Figure 6-16. Memory state of xyCar reference variable
It is interesting to note the memory state when the statement labeled #4 is executed. The statement reads
as follows:
xyCar = myCar; /* #4 */
Recall that a variable name has two things associated with it: a memory address and a value stored at that
memory address. The memory address (or location) is also known as its lvalue whereas the value stored at its
memory address is also called rvalue . When a variable is used to the left of an assignment operator ( xyCar in
statement labeled #4), it refers to its memory address. When a variable is used to the right of assignment operator
( myCar in statement labeled #4), it refers to its value ( rvalue ) stored at its memory address. The statement labeled #4
can be read as follows:
xyCar = myCar; /* #4 */
At lvalue of xyCar store rvalue of myCar; /* #4 - another way */
At memory address of xyCar store value of myCar /* #4 - another way */
Therefore, when you execute the statement xyCar = myCar , it reads the value of myCar , which is 9216 , and stores
it at the memory address of xyCar . The reference variable myCar stores a reference to a Car object. An assignment like
xyCar = myCar does not copy the object to which myCar refers. Rather, it copies the value stored in myCar (a reference
to the Car object) to xyCar . When the assignment xyCar = myCar is complete, the reference variables of myCar and
xyCar have reference to the same Car object in memory. At this point, only one Car object exists in memory.
Figure 6-17 shows the memory state when statement labeled #4 is executed.
 
Search WWH ::




Custom Search