Java: Autoboxing and unboxing
If a value of primitive type is provided where a value of wrapper type (a "boxed value") is expected, the compiler will automatically convert it. This is called autoboxing.
Example: Autoboxing in its simplest form
Integer i = 5;
The opposite conversion is called unboxing.
Example: Unboxing in its simplest form
int i = new Integer(5);
Without these automatic conversions, code would quickly get cluttered, especially when working with collections.
Unboxing a null reference
If you try to unbox a
null reference, a
NullPointerException will be thrown.
Example: Compiles but throws a
NullPointerException when executed
Integer i = null; int j = i;
Behind the scenes
The Java Language Specification does not specify exactly how the conversion should be done, but the standard implementation uses the static
Boxed.valueOf(primitive) and non-static
Boxed.primitiveValue() for boxing resp. unboxing.
Example: These two snippets are equivalent
valueOf methods of
Character caches values between −128 and 127. This means that two calls to
Integer.valueOf(5) will return the same reference, while two calls to
Integer.valueOf(5000) may not.
This can give rise to some surprising semantics when comparing boxed values using
Recommended reading: Java: Boxed values and equality.