Java Reference
In-Depth Information
references
address of where the object is stored. This memory address is called a
reference
(to the
object).
1
This is diagrammed in Display 5.12 .
Variables of a primitive type and variables of a class type are different for a reason.
A value of a primitive type, such as the type
int
, always requires the same amount of
memory to store one value. There is a maximum value of type
int
, so values of type
int
have a limit on their size. However, an object of a class type, such as an object
of the class
String
, might be of any size. The memory location for a variable of type
String
is of a fixed size, so it cannot store an arbitrarily long string. It can, however,
store the address of any string because there is a limit to the size of an address.
Because variables of a class type contain a reference (memory address), two variables
may contain the same reference, and in such a situation, both variables name the same
object. Any change to the object named by one of these variables will produce a change
to the object named by the other variable, because they are the same object. For example,
consider the following code. (The class
ToyClass
is defined in Display 5.11 , but the
meaning of the code should be obvious and you should not need to look up the definition.)
ToyClass variable1 =
new
ToyClass("Joe", 42);
ToyClass variable2;
variable2 = variable1; //Now both variables name the same object.
variable2.set("Josephine", 1);
System.out.println(variable1);
//Invokes
variable1'
s
toString
//method
The output is
Josephine 1
The object named by
variable1
has been changed without ever using the name
variable1
. This is diagrammed in Display 5.13 .
Variables of a Class Type Hold References
A variable of a primitive type stores a value of that type. However, a variable of a class
type does not store an object of that class. A variable of a class type stores the reference
(memory address) of where the object is located in the computer's memory. This causes
some operations, such as
=
and
==
, to behave quite differently for variables of a class type
than they do for variables of a primitive type.
Reference Types
A type whose variables contain references are called
reference types
. In Java, class types
are reference types, but primitive types are not reference types.
1
Readers familiar with languages that use pointers will recognize a reference as another name for a pointer.
However, Java does not use the term
pointer
, but instead uses the term
reference
. Moreover, these references are
handled automatically. There are no programmer-accessible pointer (reference) operations for dereferencing or
other pointer operations. The details are all handled automatically in Java.