Take the 2-minute tour ×

I always thought that primitive types in Java cannot be null, as it is a compile time error if i attempt to do something like this:

int test = null;

However in a ternary operation, it seems to be allowed:

int test = something != 0 ? 5 : null;

Isn't a ternary operation just short for (in this case):

int test;
if (something != 0){
    test = 5;
} else {
    test = null

which of course should not be allowed. if that condition fails, It will automaticly throw a NullPointerException due to autoboxing. So why the java-compiler doesn't fetch nonsense like this?

share|improve this question
By the way, you're talking about primitive types. Raw types are something completely different. docs.oracle.com/javase/tutorial/java/generics/rawTypes.html –  Natix Nov 8 '12 at 16:53
youre right! I just confused them, and changed it accordingly –  Rafael T Nov 9 '12 at 9:38
possible duplicate of Tricky ternary operator in Java - autoboxing –  Andy Brown Jan 19 at 17:09

1 Answer 1

up vote 9 down vote accepted

What happens is that the Java compiler first tries to make the types of the expressions on either side of the : equal. In this case, it autoboxes the 5 to an Integer; note that null is a valid value for Integer. The result of the whole ternary expression is Integer. You assign that to an int, so the Integer is then autounboxed.

Essentially the compiler applies autoboxing and -unboxing so that the line is going to look like this:

int test = (something != 0 ? Integer.valueOf(5) : null).intValue();

Indeed, autounboxing null leads to a NullPointerException.

So why the java-compiler doesn't fetch nonsense like this?

Because the designers of the Java language defined the language in such a way that it works like this and didn't decide that this has to be treated as an error...

Section 15.25 of the Java Language Specification explains how the type of the whole expression is determined.

share|improve this answer
@nhahtdh Why do you think so? –  Jesper Nov 8 '12 at 14:52
Sorry, never mind. You are right. It's confusion on my part when reading the disassembled code. –  nhahtdh Nov 8 '12 at 14:55

Your Answer


