In Java:
int count = (Integer) null;
throws a java.lang.NullPointerException.
Why doesn't this throw a Class Cast Exception for ease in programmer understanding?
Why was this exception chosen over any other exception?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityWhen executing your code, the Java runtime does the following:
In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.
EDIT
I had a related question a while ago at Stack Overflow, see here.
Java successfully casts null to an Integer reference that references no object.
That's OK because being unistantiated is a valid state for a reference.
It's the calling of a method of a non existing object that can't be performed.
Performing the cast (Integer)null
is the same as declaring an Integer variable and then failing to assign it an new (or already existing) Integer object instance.
To unbox a Integer
into a int
i.e. in int i = new Integer(15);
, i
actually equals new Integer(15).intValue()
i = (Integer) o
; where Object o = 15
is the same as o = Integer.valueOf(15);
but i = null
; throws an NullPointerException
because i
then equals null.intValue()
which throws a NullPointerException
.
valueOf()
factory methods rather than creating new instances for boxing.