img
All of the numeric type wrappers define constructors that allow an object to be constructed
from a given value, or a string representation of that value. For example, here are the
constructors defined for Integer:
Integer(int num)
Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown.
All of the type wrappers override toString( ). It returns the human-readable form of the
value contained within the wrapper. This allows you to output the value by passing a type
wrapper object to println( ), for example, without having to convert it into its primitive type.
The following program demonstrates how to use a numeric type wrapper to
encapsulate a value and then extract that value.
// Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue();
System.out.println(i + " " + iOb); // displays 100 100
}
}
This program wraps the integer value 100 inside an Integer object called iOb. The program
then obtains this value by calling intValue( ) and stores the result in i.
The process of encapsulating a value within an object is called boxing. Thus, in the program,
this line boxes the value 100 into an Integer:
Integer iOb = new Integer(100);
The process of extracting a value from a type wrapper is called unboxing. For example, the
program unboxes the value in iOb with this statement:
int i = iOb.intValue();
The same general procedure used by the preceding program to box and unbox values has
been employed since the original version of Java. However, with the release of JDK 5, Java
fundamentally improved on this through the addition of autoboxing, described next.
Autoboxing
Beginning with JDK 5, Java added two important features: autoboxing and auto-unboxing.
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( ).
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home