next up previous
Next: Graphical notation for representing Up: Unit 02 Previous: Initializing a variable

Object references

In Java, variables cannot contain objects, but only references to objects.

The objects are constructed and allocated in memory independently from the declarations of variables. Specifically:

A variable whose type is a class contains a reference to an object of the class (i.e., the address of the memory location where the object is allocated).

Example:

String s;
s = "xxx";

The first statement declares a variable s of type String. Such a variable is not initialized yet. The second statement assign to such a variable the reference to the object denoted by "xxx".

Notice that two variables may contain a reference to the same object.

Example:

String s, t;
s = "xxx";
t = s;

After these two statement, both t and s contain a reference to the object denoted by "xxx".

Variables of type object reference may have also a special value, namely null. Such a value means that the variable does not denote any object. Do not confuse variables whose value is null with variables that are not initialized. A variable that is not initialized does not have any value, not even null.


next up previous
Next: Graphical notation for representing Up: Unit 02 Previous: Initializing a variable