【发布时间】:2012-10-17 15:05:57
【问题描述】:
可能重复:
NullPointerException through auto-boxing-behavior of Java ternary 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);
}
}
这段代码编译得很好。所有表达式最终都尝试将null 分配给Integer 类型变量exp1、exp2 和exp3。
前两种情况不要抛出任何异常并产生exp1 = null exp2 = null,这是显而易见的。
然而,最后一种情况,如果你仔细看,你会看到它还试图将null 分配给Integer 类型变量exp3,看起来与前两种情况类似,但它会导致@987654333 @被抛出。为什么会这样?
在我发布我的问题之前,我已经提到了this 很好的问题,但在这种情况下,我找不到 JLS 指定的规则适用于此处。
【问题讨论】:
-
?:运算符使代码不那么明显。如果您使用了if-then-else,就不会产生混淆。 -
操作员没有抛出这个异常。 您的操作数之一在评估期间抛出了它。
标签: java nullpointerexception conditional-operator