Java Reference
In-Depth Information
This program wraps the integer value 100 inside an Integer object called iOb . The pro-
gram then obtains this value by calling intValue( ) and stores the result in i . Finally, it dis-
plays the values of i and iOb , both of which are 100.
The same general procedure used by the preceding example to manually box and unbox
values was required by all versions of Java prior to JDK 5 and may still be found in legacy
code. The problem is that it is both tedious and error-prone because it requires the program-
mer to manually create the appropriate object to wrap a value and to explicitly obtain the
proper primitive type when its value is needed. Fortunately, autoboxing/unboxing funda-
mentally improves on these essential procedures.
Autoboxing Fundamentals
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed)
into its equivalent type wrapper whenever an object of that type is needed. There is no
need to explicitly construct an object. Auto-unboxing is the process by which the value of
a boxed object is automatically extracted (unboxed) from a type wrapper when its value is
needed. There is no need to call a method such as intValue( ) or doubleValue( ) .
The addition of autoboxing and auto-unboxing greatly streamlines the coding of several
algorithms, removing the tedium of manually boxing and unboxing values. It also helps
prevent errors. With autoboxing it is not necessary to manually construct an object in order
to wrap a primitive type. You need only assign that value to a type-wrapper reference. Java
automatically constructs the object for you. For example, here is the modern way to con-
struct an Integer object that has the value 100:
Notice that the object is not explicitly created through the use of new . Java handles this for
you, automatically.
Search WWH ::




Custom Search