Possible Duplicate:
Java conditional operator ?: result type
NullPointerException through auto-boxing-behavior of Java ternary operator
Say I have two functions:
f(MyObject o) { ... }
f(int i) { ... }
And I call them like this:
f(someCondition ? 10 : null);
This compiles, but when I run it I get a null pointer exception (sorry I’m not sure on which condition). Some my questions are:
- Why does it even compile? What is the type of
foo ? 10 : null? - It clearly doesn’t call the “correct” functions because that wouldn’t cause an NPE. So which function is it calling? Does it do
f((MyObject)10);orf((int)null)?
First of all, the problem doesn’t have anything to do with the fact that you have overloaded versions of
f. If you only have the version offthat takes anint, you get the same problem.The thing is that both possible results of the ternary expression (before and after the
:) must have the same type, because the whole expressioncondition ? expr1 : expr2must have a single type. You can’t have this expression evaluate to one type ofconditionistrue, and another type if it isfalse.So, the Java compiler is going to see if it can convert
expr1andexpr2to a single type. Note thatintcannot benull(because it’s a primitive type). However,10can be converted toIntegervia autoboxing, and anIntegercan also benull. So the type of the whole ternary expression is determined to be of typeInteger. The result is either anIntegerthat contains the value10or anIntegerthat isnull.Step two is that you pass this
Integertof. Becauseftakes anint, it is auto-unboxed.If you auto-unbox an
Integerthat isnull, you get aNullPointerException– that’s what happens here.