In Java, wrapper classes (Integer, Float, Double, etc.) are objects that can hold a reference to a value. Being objects, they can hold null to represent the absence of a value, which is a valid reference for any object type in Java.
On the other hand, primitive types (int, float, double, etc.) are not objects; they hold simple, direct values. Primitive types cannot store null because null represents the lack of an object reference, and primitive types are not objects—they must always hold a concrete value (e.g., 0, false).
Unboxing a null Causes NullPointerException
When you try to unbox a null value from a wrapper class (e.g., Integer), Java tries to convert null into a primitive type, which isn't possible. This will result in a NullPointerException.
Code Example Demonstrating NullPointerException Due to Unboxing a null:
public class NullUnboxingExample {
public static void main(String[] args) {
// Create an Integer wrapper object and assign it a null value
Integer number = null;
try {
// Unboxing: Attempting to convert 'null' to primitive 'int'
int value = number; // This will throw a NullPointerException
System.out.println("Value: " + value);
} catch (NullPointerException e) {
System.out.println("Caught a NullPointerException: Cannot unbox a null value into a primitive.");
}
}
}
Explanation:
-
Wrapper Class (
Integer) Holdingnull: TheIntegervariablenumberis set tonull, which is valid becauseIntegeris an object. -
Unboxing
null: When we try to unbox theIntegerinto a primitiveint(i.e.,int value = number;), Java tries to convert thenullreference into a primitive value, which isn't possible. This results in aNullPointerException.
Output:
Caught a NullPointerException: Cannot unbox a null value into a primitive.
Key Takeaways:
- Wrapper classes can hold
nullbecause they are objects. - Primitive types cannot hold
nullbecause they represent direct, non-object values. - Unboxing a
nullvalue will lead to aNullPointerException, so you need to check fornullbefore performing unboxing in your code.
Top comments (0)