Java – Why Use Null Pointer Instead of Class Cast?

javalanguage-design

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?

Best Answer

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.