Tin*_*iny 7 java nullpointerexception conditional-operator
以下代码使用简单的条件运算符.
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)
这段代码编译得很好.所有表达式最终试图向null到Integer输入变量exp1,exp2并exp3分别.
前两种情况不会抛出任何异常并产生exp1 = null exp2 = null明显的异常.
然而,最后一种情况,如果你仔细检查它,你会看到它也试图分配null给Integer类型变量exp3并看起来类似于前两种情况,但它会导致NulllPointerException抛出.为什么会这样?
在我发布我的问题之前,我已经提到了这个不错的问题,但在这种情况下,我找不到JLS指定的规则在这里应用.
Bal*_*usC 13
在null正在拆箱到的int,因为赋值是由于5一个int,不是Integer.但是,a null不能表示为int,因此NullPointerException.
如果更换5的new Integer(5),那么它会工作.
Integer exp3 = false ? new Integer(5) : true ? null : 50;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
330 次 |
| 最近记录: |