Java: Autoboxing and unboxing

If a value of primitive type (int, double, boolean, …) is provided where a value of wrapper type (a “boxed value” such as Integer, Double, Boolean, …) is expected, the compiler will automatically convert it. This is called autoboxing.

Example: Autoboxing in its simplest form

Integer i = 5;  // int turned into an Integer

The opposite conversion is called unboxing.

Example: Unboxing in its simplest form

int i = new Integer(5);  // Integer turned into an int

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 javac reference implementation uses the following methods:

Type Boxing Unboxing

byte

Byte.valueOf Byte.byteValue

short

Short.valueOf Short.shortValue

int

Integer.valueOf Integer.intValue

long

Long.valueOf Long.longValue

float

Float.valueOf Float.floatValue

double

Double.valueOf Double.doubleValue

char

Character.valueOf Character.charValue

boolean

Boolean.valueOf Boolean.booleanValue

Example: These two snippets are equivalent

Integer i = 1;
Integer j = 2;
Integer k = i + j;
Integer i = Integer.valueOf(1);
Integer j = Integer.valueOf(2);
Integer k = Integer.valueOf(i.intValue() + j.intValue());

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

Be the first to comment!