Wrapper classes and autoboxing
Move between int and Integer on purpose, and avoid the null and == surprises.
Open this lesson in the learning hubKey points
- Every primitive has an object wrapper:
int/Integer,double/Double,boolean/Boolean. - Generics only hold objects, so it is
List<Integer>—List<int>does not exist. - Autoboxing converts both ways automatically. Convenient, but every box is a real object allocation.
- Unboxing a
nullwrapper throwsNullPointerException. This is the number one autoboxing bug. - Compare wrappers with
equals().==appears to work for -128..127 only because those come from a shared cache. - Wrappers carry the useful statics:
Integer.parseInt,Integer.MAX_VALUE,Double.compare.
Example
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(7);
int back = list.get(0);
System.out.println("boxed into the list, unboxed back out: " + back);
Integer x = 127, y = 127;
Integer p = 128, q = 128;
System.out.println("127 == 127 : " + (x == y) + " (same cached object)");
System.out.println("128 == 128 : " + (p == q) + " (two different objects)");
System.out.println("p.equals(q) : " + p.equals(q));
System.out.println("parseInt: " + (Integer.parseInt("21") * 2));
System.out.println("binary of 10: " + Integer.toBinaryString(10));
System.out.println("Double.compare(1.5, 2.5): " + Double.compare(1.5, 2.5));
Integer missing = null;
try {
int boom = missing;
System.out.println(boom);
} catch (NullPointerException e) {
System.out.println("unboxing null throws NullPointerException");
}
}
}
Boxing is automatic; the NullPointerException it hides is not.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.