Java Reference
In-Depth Information
model
Unknown
year
2000
262144
price
0.0
Memory address
Object stored at the address
Figure 6-13.
Memory state when a Car object is created using the new Car() statement
At this point, there is no way to refer to the newly created
Car
object from a Java program even though it exists in
memory. The
new
operator (as used in
new Car()
) returns the memory address of the object it creates. In your case, it
will return
262144
. Recall that the memory address of the data (the
Car
object, in your case) is also called as reference
of that data. From now onwards you will say that the
new
operator in Java returns a reference to the object it creates
instead of saying that it returns the memory address of the object. Both mean the same thing. However, Java uses the
term “reference,” which has a more generic meaning than “memory address.” In order to access the newly created
Car
object, you must store its reference in a reference variable. Recall that a reference variable stores the reference to some
data, which is stored somewhere else. All variables that you declare of reference type are reference variables in Java.
A reference variable in Java can store a
null
reference, which means that it refers to nothing. Consider the following
snippet of code that performs different things on reference variables:
Car myCar = null; /* #1 */
myCar = new Car(); /* #2 */
Car xyCar = null; /* #3 */
xyCar = myCar; /* $4 */
When the statement labeled #1 is executed, memory is allocated for
myCar
reference variable, say at memory
address
8192
. The
null
value is a special value, typically a memory address of zero, which is stored at the memory
address of the
myCar
variable. Figure
6-14
depicts the memory state for the
myCar
variable when it is assigned a
null
reference.
myCar
8192
null
Figure 6-14.
Memory state for the myCar variable, when the “Car myCar = null” statement is executed
The execution of statement labeled #2 is a two-step process. First, it executes the
new Car()
part of the statement
to create a new
Car
object. Suppose the new
Car
object is allocated at memory address of 9216. The
new Car()
expression returns the reference of the new object, which is
9216
. In the second step, the reference of the new object is
stored in
myCar
reference variable. The memory state for the
myCar
reference variable and the new
Car
object after the
statement labeled #2 is executed is shown in Figure
6-15
. Note that the memory address of the new
Car
object (
9216
)
and the value of the
myCar
reference variable match at this point. You do not need to worry about the numbers used
in this example for memory addresses; I just made up some numbers to drive home the point of how the memory
addresses are used internally. Java does not let you access the memory address of an object or a variable. Java lets you
access/modify the state of objects through reference variables.