Unexpected NullPointerException (NPE) in ternary conditional operator in Java

Sometimes I come across Java code that unexpectedly throws NullPointerException in ternary operator. It is especially surprising if this particular line of code seems very simple like:

String value = null;
Integer defaultValue = null;
Integer result = (value != null ? Integer.parseInt(value) : defaultValue);

or even:

int value = -1;
Integer defaultValue = null;
Integer result = (value > 0 ? value : defaultValue);

At first, it might look like the condition is not met so defaultValue would be assigned to result.
In fact, the second argument of ternary operator is of type int and the third argument is of type Integer. The compiler than decides that the type of the whole expression will be plain int. and tries to unbox defaultValue which is actually null. This results in NullPointerException. The type of the variable result on the left side of the expression is ignored.

The decision that the type of the whole expression should be plain int instead of Integer conforms to JLS (Java Language Specification) and is explicitly based on tables in the specification.


About Robert Piasecki

Husband and father, Java software developer, Linux and open-source fan.
This entry was posted in Java, Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.