Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Types and Literals

Autoboxing and unboxing

Reference for Java autoboxing and unboxing: automatic conversion between primitives and wrappers, the Integer cache, null unboxing and overload surprises.

Autoboxing is the compiler's automatic conversion of a primitive value into its wrapper object (int to Integer). Unboxing is the reverse. Both are inserted silently wherever the types require it: assigning to a wrapper variable, adding to a List<Integer>, passing to a method, or using arithmetic on a wrapper.

Boxing is convenient, but it hides three things: object allocation, the possibility of NullPointerException, and the difference between == and equals(). Most boxing bugs come from one of these.

Java
Integer boxed = 5;       // autoboxing: Integer.valueOf(5)
int plain = boxed + 1;   // unboxing: boxed.intValue() + 1

Try it

Java The Integer cache and equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Null, ternaries and overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

The compiler rewrites boxing into calls to valueOf() and unboxing into calls to xxxValue():

You write Compiler emits
Integer i = 5; Integer i = Integer.valueOf(5);
int n = i; int n = i.intValue();
i++ i = Integer.valueOf(i.intValue() + 1)
double d = dObj; dObj.doubleValue()

Boxing only converts to the exact wrapper: Long l = 5; does not compile (an int cannot box to Long), while long l = 5; and Long l = 5L; do. Object o = 5 boxes to Integer.

Usage notes

  • Cache range. Integer.valueOf(), Long.valueOf(), Short.valueOf() and Byte.valueOf() return cached objects for -128 to 127 (the upper bound of Integer's cache can be raised with a JVM flag). Never rely on == for wrappers.
  • Null unboxing throws NullPointerException, commonly from Map.get(), from a database value, or from a ternary like cond ? 1 : nullableInteger.
  • Performance. Boxing in a hot loop allocates objects. Long sum = 0L; for (...) sum += i; creates a new Long on each iteration. Use a primitive accumulator, or primitive streams such as IntStream.
  • Overloads. The compiler first tries widening without boxing, then boxing, then varargs. That is why show(5) above picks long over Integer.
  • List.remove has both remove(int index) and remove(Object o); a plain int argument picks the index version.
  • Arrays do not box. int[] is not an Integer[] and cannot be passed as List<Integer> through Arrays.asList.
  • Generics require boxing: List<int> is not legal.