Easy java core-java

What is the difference between primitives and wrapper classes, and what is autoboxing?

The 30 second answer

Primitives like int, long and boolean hold the value directly, can't be null and are cheap. Wrappers like Integer are objects, so they can be null and can go into collections. Autoboxing converts int to Integer automatically and unboxing does the reverse. Two traps: unboxing a null Integer throws NullPointerException, and comparing two Integers with == checks identity, which happens to work for -128 to 127 because of the cache but fails for 128. Always compare wrappers with equals.

<!-- level: 1 --> <!-- must_know: true -->

Java has eight primitive types: byte, short, int, long, float, double, char, boolean. Each has a wrapper class (Integer, Long and so on). Collections only hold objects, so List<Integer> boxes each value.

Integer a = 127, b = 127, c = 128, d = 128;
a == b;        // true
c == d;        // false on a default JVM
c.equals(d);   // true

Integer missing = null;
int n = missing;   // NullPointerException on unboxing

Why 127 == 127 is true: the Java Language Specification requires that boxing an int between -128 and 127 always returns the same object, and Integer.valueOf caches that range. Values outside it may be new objects; the upper bound can be raised with a JVM option, so 128 == 128 being false is typical but not something to rely on either way. The rule is simply to compare wrappers with equals or unbox them first.

Performance note: boxing in a hot loop creates garbage. Use primitive arrays or IntStream where it matters.

Sources (2)
  1. Java Language Specification, chapter 5: Conversions and contexts (5.1.7 Boxing conversion)docs.oracle.com
  2. Javadoc: java.lang.Integer (valueOf)docs.oracle.com