What are wrapper classes in Java?
Java has eight primitive types — `byte`, `short`, `int`, `long`, `float`, `double`, `char`, and `boolean` — that are not objects and cannot be used where `Object` references are required. Wrapper classes provide an object counterpart for each: `Byte`, `Short`, `Integer`, `Long`, `Float`, `Double`, `Character`, and `Boolean`.
The primary motivation is interoperability with the Java Collections Framework. `ArrayList<int>` is illegal — generics require reference types. You write `ArrayList<Integer>` instead. Wrapper classes bridge the gap.
Java 5 introduced autoboxing and unboxing to reduce boilerplate. Autoboxing is the automatic conversion from primitive to wrapper (`int` → `Integer`); unboxing is the reverse. The compiler inserts the conversion calls transparently, so `Integer i = 5` compiles to `Integer.valueOf(5)`, and `int x = i` compiles to `i.intValue()`.
Wrapper classes also carry utility methods. `Integer.parseInt("42")` converts strings to primitives. `Integer.MAX_VALUE`, `Integer.MIN_VALUE`, `Integer.toBinaryString()` are all available on the class. This makes them useful beyond mere boxing.
A critical performance and correctness caveat: `Integer` (and other integer wrappers) caches instances for values from -128 to 127. `Integer.valueOf(100) == Integer.valueOf(100)` is `true` because both return the cached instance. `Integer.valueOf(200) == Integer.valueOf(200)` is `false` — new objects. This is a common source of subtle bugs when using `==` instead of `equals()` with wrapper types.
Another pitfall is NullPointerException during unboxing. If an `Integer` field is null and you assign it to an `int`, the JVM calls `.intValue()` on null and throws NPE. This happens invisibly because the unboxing is compiler-generated.
Explains the purpose of wrapping primitives for use in collections/generics and describes autoboxing/unboxing.
Also covers the Integer cache (-128 to 127), the == vs equals() trap, utility methods on wrapper classes, and NPE risk from unboxing null.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment