DEV Community

Abhishek Kumar
Abhishek Kumar

Posted on

Why `null` is Allowed for Wrapper Classes but Not for Primitives

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.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Wrapper Class (Integer) Holding null: The Integer variable number is set to null, which is valid because Integer is an object.
  2. Unboxing null: When we try to unbox the Integer into a primitive int (i.e., int value = number;), Java tries to convert the null reference into a primitive value, which isn't possible. This results in a NullPointerException.

Output:

Caught a NullPointerException: Cannot unbox a null value into a primitive.
Enter fullscreen mode Exit fullscreen mode

Key Takeaways:

  • Wrapper classes can hold null because they are objects.
  • Primitive types cannot hold null because they represent direct, non-object values.
  • Unboxing a null value will lead to a NullPointerException, so you need to check for null before performing unboxing in your code.

Top comments (0)