Java Reference
In-Depth Information
// Display the result using int variables
System.out.println(iValue + " + " + jValue + " = " + kValue);
}
}
200 + 300 = 500
Note the amount of code needed just to add two
int
values. Wrapping/unwrapping an
int
value to an
Integer
and vice versa is just a pain for Java developers. Java designers realized it (though too late) and they automated this
wrapping and unwrapping process for you.
The automatic wrapping from a primitive data type (
byte
,
short
,
int
,
long
,
float
,
double
,
char
and
boolean
)
to its corresponding wrapper object (
Byte
,
Integer
,
Long
,
Float
,
Double
,
Character
and
Boolean
) is called
autoboxingThe reverse, unwrapping from wrapper object to its corresponding primitive data type, is called unboxing.
With autoboxing/unboxing, the following code is valid:
Integer n = 200; // Boxing
int a = n; // Unboxing
The compiler will replace the above statement with the following:
Integer n = Integer.valueOf(200);
int a = n.intValue();
The code in the
main()
method of the
MathUtil
class listed in Listing 8-2 can be rewritten as follows. The boxing
and unboxing are done for you automatically.
int iValue = 200;
int jValue = 300;
int kValue = MathUtil.add(iValue, jValue);
System.out.println(iValue + " + " + jValue + " = " + kValue);
■
autoboxing/unboxing is performed when you compile the code. the JVM is completely unaware of the boxing
and unboxing performed by the compiler.
Tip
Beware of Null Values
Autoboxing/unboxing does save you from writing additional lines of codes. It also makes your code look neater.
However, it does come with some surprises. One of the surprises is getting a
NullPointerException
where you would
not expect it to happen. Primitive types cannot have a
null
value assigned to them, whereas reference types can have
a
null
value. The boxing and unboxing happens between primitive types and reference types. Look at the following
snippet of code:
Integer n = null; // n can be assigned a null value
int a = n; // will throw NullPointerException at run time