What are Java's wrapper classes, why do they exist, and when should you prefer one over the primitive?
A wrapper class wraps a primitive value inside an object. There is one for each primitive, so int has Integer, double has Double and boolean has Boolean, plus the two special cases Character and Void. Each wrapper is a final class with one private field that holds the primitive value.
They exist for three reasons.
First, generics cannot be given a primitive type. The type argument List<Integer> is legal, while List<int> is not, so anything that has to live inside a collection, a stream or an optional value needs a wrapper.
Second, the class library was written before generics existed, so it had to work with objects. That is why the older collection classes were built around wrappers.
Third, wrappers carry behaviour that primitives cannot. The methods Integer.parseInt, Integer.toBinaryString, Character.isDigit and Boolean.parseBoolean all live on the wrapper classes.
So when should you prefer the primitive? Use it for fields, for method parameters and for return types on a busy path. A wrapper is an object on the heap, so a field of type Integer holds a reference that has to be followed, it may be null, and it adds work for the garbage collector. A field of type int holds the value directly, with no reference and no possibility of being null.
When should you prefer the wrapper? Use it for generic containers, for values that may genuinely be missing, and for any API that asks for an object type.
The recurring trap is that a wrapper can be null and a primitive cannot. Any operation that takes a null wrapper apart throws a NullPointerException at the point where you use it, and that point is often a long way from the place where the null first appeared.
The next question in this topic shows how to move between the two forms.