Wrapper Classes and Autoboxing
Explore how Java bridges primitive types and objects through wrapper classes and automatic autoboxing. Understand the conversion rules, risks such as NullPointerExceptions, and how to correctly compare wrapper objects to write safer, more effective code.
We have already seen how Java uses primitive types like int and double to handle data efficiently. However, primitives have a significant limitation: they are not objects. However, primitives are not objects. They cannot be assigned null, and they cannot be used where an object is required, such as in generic collections. We’ll cover generics later.
To bridge this gap, Java provides wrapper classes, which allow us to treat primitive values as full-fledged objects. In this lesson, we will see how Java automates the translation between these two worlds and how to avoid the specific bugs this convenience can introduce.
The role of wrapper classes
For every primitive type in Java, there is a corresponding class in the java.lang package. These classes wrap primitive values in an object.
Primitive type | Wrapper class |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Using a wrapper class is necessary when we need to distinguish between a valid default value (like 0) and no value (null). For example, in a banking app, an account balance of 0 is very different from a null balance (which might imply the account data hasn’t loaded yet).
Since Java 9, the constructors for these classes (e.g., new Integer(5)) have been deprecated. Instead, we use static factory methods like valueOf(). These methods are more efficient because they can reuse commonly used objects rather than creating new ones every time. ... ...