Java Reference
In-Depth Information
The value
754
is directly stored at the memory address
131072
, which is associated with the
id
variable name.
What happens if you execute the following statement, which assigns a new value of
351
to the
id
variable?
id = 351;
When a new value
351
is assigned to the
id
variable, the old value of
754
is replaced with the new value at the
memory address as shown in Figure
6-12
.
131072
id
351
Variable name
Value stored at the address
Memory address
Figure 6-12.
The memory state for an id variable when a new value of 351 is assigned to it
Things are different when you work with objects and reference variables. Let's consider the declaration of a
Car
class as shown in Listing 6-21. It has three instance variables:
model
,
year
, and
price
, which have been given initial
values of
"Unknown"
,
2000
, and
0.0
, respectively.
Listing 6-21.
Car Class with Three Public Instance Variables
// Car.java
package com.jdojo.cls;
public class Car {
public String model = "Unknown";
public int year = 2000;
public double price = 0.0;
}
When you create an object of a reference type, the object is created on the heap and it is stored at a specific
memory address. Let's create an object of the
Car
class as follows:
new Car();
Figure
6-13
shows the memory state when the above statement is executed to create a
Car
object. You probably
assumed that the memory address where the object is stored is
262144
. Notice that when an object is created, memory
is allocated for all of its instance variables and they are initialized. In this case,
model
,
year
, and
price
of the new
Car
object have been initialized properly, as shown in the figure.