Java Reference
In-Depth Information
As an example, in Figure 2.1 are two objects of type Point . It happens, by
chance, that these objects are stored in memory locations 1000 and 1024,
respectively. For these two objects, there are three references: point1 , point2 ,
and point3 . point1 and point3 both reference the object stored at memory
location 1000; point2 references the object stored at memory location 1024.
Both point1 and point3 store the value 1000, while point2 stores the value
1024. Note that the actual locations, such as 1000 and 1024, are assigned by
the runtime system at its discretion (when it finds available memory). Thus
these values are not useful externally as numbers. However, the fact that
point1 and point3 store identical values is useful: It means they are referenc-
ing the same object.
A reference will always store the memory address where some object is
residing, unless it is not currently referencing any object. In this case, it will
store the null reference, null . Java does not allow references to primitive
variables.
There are two broad categories of operations that can be applied to refer-
ence variables. One allows us to examine or manipulate the reference value.
For instance, if we change the stored value of point1 (which is 1000), we
could have it reference another object. We can also compare point1 and point3
and determine if they are referencing the same object. The other category of
operations applies to the object being referenced; perhaps we could examine
or change the internal state of one of the Point objects. For instance, we could
examine some of Point 's x and y coordinates.
Before we describe what can be done with references, let us see what is
not allowed. Consider the expression point1*point2 . Since the stored values of
point1 and point2 are 1000 and 1024, respectively, their product would be
1024000. However, this is a meaningless calculation that could not have any
possible use. Reference variables store addresses, and there is no logical
meaning that can be associated with multiplying two addresses.
figure 2.1
An illustration of a
reference. The Point
object stored at
memory location
1000 is referenced
by both point1 and
point3 . The Point
object stored at
memory location
1024 is referenced
by point2 . The
memory locations
where the variables
are stored are
arbitrary.
1000
( 0, 0 )
point1
( 0, 0 )
1024
( 5, 12 )
point2 = 1024
point1 = 1000
point3 = 1000
(at 1000)
3200
point2
( 5, 12 )
3600
(at 1024)
5124
point3
 
Search WWH ::




Custom Search