Wrapper Types And Autoboxing
Generics and collections work with reference types, not primitives. Every primitive has a wrapper class:
| Primitive | Wrapper class |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Autoboxing converts a primitive to its wrapper when needed. Unboxing performs the reverse conversion, often without explicit syntax.
Move between int and Integer
public class Main {
public static void main(String[] args) {
Integer boxed = Integer.valueOf(91);
int unboxed = boxed.intValue();
System.out.println(boxed.getClass().getSimpleName());
System.out.println(unboxed + 1);
}
}
Output:
Integer
92
valueOf and intValue show the conversions explicitly. Autoboxing lets Java insert equivalent conversions when a primitive is assigned to a wrapper or a wrapper is used as a primitive.
Unboxing null throws NullPointerException. A nullable wrapper needs a check before Java treats it as a primitive.
Box the temperature as an Integer, then unbox it and add two degrees.