Why `null` is Allowed for Wrapper Classes but Not for Primitives
Abhishek Kumar
Posted on October 2, 2024
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
: TheInteger
variablenumber
is set tonull
, which is valid becauseInteger
is an object. -
Unboxing
null
: When we try to unbox theInteger
into a primitiveint
(i.e.,int value = number;
), Java tries to convert thenull
reference 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
null
because they are objects. - Primitive types cannot hold
null
because they represent direct, non-object values. - Unboxing a
null
value will lead to aNullPointerException
, so you need to check fornull
before performing unboxing in your code.
Posted on October 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024