Java: Autoboxing and unboxing

If you're not already familiar with wrapper types, please start here: Java: Wrapper Types

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
Integer i = 1;
Integer j = 2;
Integer k = i + j;

Caching

The valueOf methods of Byte, Short, Integer, Long and 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 == and !=.

Recommended reading: Java: Boxed values and equality.

Comments