Java Reference
In-Depth Information
Understanding References
A reference is (typically) a 32-bit integer value that contains the memory address of the
object it refers to. I use the term “typically” because the size of a reference is not strictly
defined in the Java Language Specification. In the future, references will likely be 64-bit
integers or larger. Similarly, they can be smaller than 32 bits when used with operating sys-
tems for small electronic devices.
Because references are essentially integers, you may wonder why they need to be
declared as a particular data type. This is because data types are strictly enforced in Java. A
reference must be of a particular class data type.
For example, in the following statements, two Employee references and one String ref-
erence are allocated in memory.
Employee e1, e2;
String s;
Each of these three references consumes the same amount of memory and is essentially
an integer data type. However, the references e1 and e2 can refer only to Employee
objects. The reference s can refer only to a String object. To illustrate this point, the follow-
ing statements attempt to break this rule and are not valid:
s = new Employee(); //Does not compile
e1 = “Rich”; //Does not compile
You might think that using the cast operator could create a work-around to this situation:
e1 = new Employee(); //Valid
s = e1; //Does not compile
s = (Employee) e1; //Still doesn't compile
However, the compiler knows that String objects and Employee objects are not com-
patible and will generate compiler errors in the statements above. (Other languages such
as C++ have similar data type concerns, but they are often not as strictly enforced as they
are in Java.)
The references e1 and e2 are the same data type and can be assigned to each other.
For example:
e1 = new Employee();
e2 = e1; //Valid
The e1 reference is assigned to a new Employee object, and the e2 reference is
assigned to e1. This is valid because e1 and e2 are both Employee references and there-
fore are the same data type. This new Employee object now has two references pointing
to it. (Note that there is only one Employee object in memory because we only used the
new keyword once. Assigning e1 to e2 does not create a new object.)
We could have declared the reference e and instantiated the Employee object
in a single statement:
Employee e = new Employee();
Search WWH ::




Custom Search