Java Reference
In-Depth Information
Figure 1-7.
A handle is stored in
ages
, and the list entry identified by this handle stores the
address of the associated array.
Handlesmakeiteasytomovearoundregionsofmemoryduringgarbagecollection
(discussedin
Chapter2
).Ifmultiplevariablesreferencedthesamearrayviathesame
address,eachvariable'saddressvaluewouldhavetobeupdatedwhenthearraywas
moved.However,ifmultiplevariablesreferencedthearrayviathesamehandle,only
the handle's list entry would need to be updated. A downside to using handles is
that accessing memory via these handles can be slower than directly accessing this
memory via an address. Regardless of how references are implemented, this imple-
mentation detail is hidden from the Java developer in order to promote portability.
Thefollowingexampleshowsasimpleexpressionwhereonevariableisassignedthe
value of another variable:
int counter1 = 1;
int counter2 = counter1;
Finally,thefollowingexampleshowsasimpleexpressionthatassignstheresultofa
method call to a variable named
isLeap
:
boolean isLeap = isLeapYear(2011);
Thepreviousexampleshaveassumedthatonlythoseexpressionswhosetypesarethe
sameasthetypesofthevariablesthattheyareinitializingcanbeassignedtothosevari-
ables.However,undercertaincircumstances,it'spossibletoassignanexpressionhav-
ing a different type. For example, Java permits you to assign certain integer literals to
shortintegervariables,asin
short s = 20;
,andassignashortintegerexpression
to an integer variable, as in
int i = s;
.
Javapermitstheformerassignmentbecause
20
canberepresentedasashortinteger
(noinformationislost).Incontrast,Javawouldcomplainabout
short s = 40000;
because integer literal
40000
cannot be represented as a short integer (32767 is the
maximum positive integer that can be stored in a short integer variable). Java permits