27

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?

asked Jul 31, 2012 at 17:16
0

3 Answers 3

49

When executing your code, the Java runtime does the following:

  1. Cast null to an object of class Integer.
  2. Try to unbox the Integer object to an int by calling the method intValue()
  3. Calling a method on a null object throws a NullPointerException.

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.

answered Jul 31, 2012 at 17:19
1

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.

gnat
20.5k29 gold badges117 silver badges308 bronze badges
answered Aug 16, 2012 at 13:58
-1

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.

Martijn Pieters
14.7k10 gold badges60 silver badges59 bronze badges
answered May 5, 2014 at 18:42
1
  • 2
    The answer that was accepted almost two years ago provides almost the same explanation, but is more clear. This answer is also not correct for Java 5+: it now uses the valueOf() factory methods rather than creating new instances for boxing. Commented May 5, 2014 at 19:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.