Java Reference
In-Depth Information
type wrapper class (see Chapter 4 ) such as Integer , and then storing this primitive
type wrapper class instance in the collection—see the following example:
Collection<Integer> col = ...; // This code does not com-
pile because of the “...”.
int x = 27;
col.add(new Integer(x)); // Indirectly store int value 27
via an Integer object.
Thereversesituationisalsotedious.Whenyouwanttoretrievethe int from col ,
you must invoke Integer 's intValue() method (which, if you recall, is inher-
itedfrom Integer 's java.lang.Number superclass).Continuingonfromthisex-
ample,youwouldspecify int y = col.iterator().next().intValue();
to assign the stored 32-bit integer to y .
Toalleviatethistedium,Java5introducedautoboxingandunboxing,whichareapair
of complementary syntactic sugar-based language features that make primitive values
appear more like objects. (This “sleight of hand” is not complete because you cannot
specify expressions such as 27.doubleValue() .)
Autoboxing automatically boxes (wraps)aprimitivevalueinanobjectoftheappro-
priateprimitivetypewrapperclasswheneveraprimitivetypeisspecifiedbutareference
isrequired.Forexample,youcouldchangetheexample'sthirdlineto col.add(x);
and have the compiler box x into an Integer object.
Unboxing automatically unboxes (unwraps)aprimitivevaluefromitswrapperobject
whenever a reference is specified but a primitive type is required. For example, you
couldspecify int y = col.iterator().next(); andhavethecompilerunbox
the returned Integer object to int value 27 prior to the assignment.
Althoughautoboxingandunboxingwereintroducedtosimplifyworkingwithprimit-
ivevaluesinacollectionscontext,theselanguagefeaturescanbeusedinothercontexts,
andthisarbitraryusecanleadtoaproblemthatisdifficulttounderstandwithoutknow-
ledge of what is happening behind the scenes. Consider the following example:
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2); // Output: true
System.out.println(i1 < i2); // Output: false
System.out.println(i1 > i2); // Output: false
System.out.println(i1+i2); // Output: 254
i1 = 30000;
i2 = 30000;
Search WWH ::




Custom Search