Java Reference
In-Depth Information
As of Java 5.0, Java has simplified the wrapping and unwrapping of primitive type values,
called the autoboxing and auto-unboxing of primitive types. For example, consider
the following statements:
int x; //Line 3
Integer num; //Line 4
The statement in Line 3 declares the int variable x ; the statement in Line 4 declares num
to be a reference variable of type Integer .
Consider the statement:
num = 25; //Line 5
For the most part, this statement is equivalent to the statement:
num = new Integer(25); //Line 6
That is, after the execution of either of these statements, num refers to or points to an
Integer object with value 25. The expression in Line 5 is referred to as autoboxing
of int type.
6
In reality, for the statement in Line 5, if an Integer object with value 25 already exists,
then num would point to that object. On the other hand, if the statement in Line 6
executes, then an Integer object with value 25 will be created, even if such an object
exists, and num would point to that object. In either case, num would point to an
Integer object with value 25 .
Now consider the statement:
x = num; //Line 7
This statement is equivalent to the statement:
x = num.intValue();
//Line 8
After the execution of either the statement in Line 7 or Line 8, the value of x is 25 . The
statement in Line 7 is referred to as auto-unboxing of int type.
Autoboxing and -unboxing of primitive types are features of Java 5.0 and are not available
in Java versions lower than 5.0.
Next, consider the following statement:
x = 2 * num;
//Line 9
This statement first unboxes the value of the object num , which is 25 , multiplies this value
by 2 , and then stores the value, which is 50 , into x . This illustrates that unboxing also
occurs in an expression.
 
Search WWH ::




Custom Search