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.
Integer boxed = 5; // autoboxing: Integer.valueOf(5) int plain = boxed + 1; // unboxing: boxed.intValue() + 1
Try it
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.
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()andByte.valueOf()return cached objects for -128 to 127 (the upper bound ofInteger's cache can be raised with a JVM flag). Never rely on==for wrappers. - Null unboxing throws
NullPointerException, commonly fromMap.get(), from a database value, or from a ternary likecond ? 1 : nullableInteger. - Performance. Boxing in a hot loop allocates objects.
Long sum = 0L; for (...) sum += i;creates a newLongon each iteration. Use a primitive accumulator, or primitive streams such asIntStream. - Overloads. The compiler first tries widening without boxing, then boxing, then varargs. That is why
show(5)above pickslongoverInteger. List.removehas bothremove(int index)andremove(Object o); a plainintargument picks the index version.- Arrays do not box.
int[]is not anInteger[]and cannot be passed asList<Integer>throughArrays.asList. - Generics require boxing:
List<int>is not legal.
Related
- Wrapper classes
- int
- null
- IntStream
- Tutorial: Wrapper classes