Java中的条件运算符会抛出意外的NullPointerException

Tin*_*iny 7 java nullpointerexception conditional-operator

可能重复:
通过Java三元运算符的自动装箱行为的NullPointerException

以下代码使用简单的条件运算符.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译得很好.所有表达式最终试图向nullInteger输入变量exp1,exp2exp3分别.

前两种情况不会抛出任何异常并产生exp1 = null exp2 = null明显的异常.

然而,最后一种情况,如果你仔细检查它,你会看到它也试图分配nullInteger类型变量exp3并看起来类似于前两种情况,但它会导致NulllPointerException抛出.为什么会这样?

在我发布我的问题之前,我已经提到了这个不错的问题,但在这种情况下,我找不到JLS指定的规则在这里应用.

Bal*_*usC 13

null正在拆箱到的int,因为赋值是由于5一个int,不是Integer.但是,a null不能表示为int,因此NullPointerException.

如果更换5new Integer(5),那么它会工作.

Integer exp3 = false ? new Integer(5) : true ? null : 50;
Run Code Online (Sandbox Code Playgroud)

也可以看看: