Possible Duplicate:
NullPointerException through auto-boxing-behavior of Java ternary operator
The following code uses simple conditional operators.
public class Main
{
public static void main(String[] args)
{
Integer exp1 = true ? null : 5;
Integer exp2 = true ? null : true ? null : 50;
System.out.println("exp1 = " +exp1+" exp2 = "+exp2);
Integer exp3 = false ? 5 : true ? null: 50; //Causes the NullPointerException to be thrown.
System.out.println("exp3 = "+exp3);
}
}
This code compiles fine. All the expressions ultimately attempt to assign null
to Integer
type variables exp1
, exp2
and exp3
respectively.
The first two cases don't throw any exception and produce exp1 = null exp2 = null
which is obvious.
The last case however, if you go through it carefully, you will see it also attempts to assign null
to Integer
type variable exp3
and looks something similar to the preceding two cases but it causes the NulllPointerException
to be thrown. Why does it happen?
Before I posted my question, I have referred to this nice question but in this case, I couldn't find what rules as specified by JLS are applied here.