我找不到规范中相关的部分来回答这个问题。在 Java 中的条件运算符语句中,真值和假值的参数都会被计算吗?
那么下面的代码是否可能会抛出 NullPointerException 呢?
Integer test = null;
test != null ? test.intValue() : 0;
我找不到规范中相关的部分来回答这个问题。在 Java 中的条件运算符语句中,真值和假值的参数都会被计算吗?
那么下面的代码是否可能会抛出 NullPointerException 呢?
Integer test = null;
test != null ? test.intValue() : 0;
我知道这是一篇旧帖子,但看看非常相似的情况,然后给我投票:P
回答原问题:只评估一个操作数,但:
@Test
public void test()
{
Integer A = null;
Integer B = null;
Integer chosenInteger = A != null ? A.intValue() : B;
}
NullPointerException
,而在这种情况下 IF 语句不等同于 ?: 运算符。对于“如果第二个和第三个操作数中的一个是
boolean
类型,而另一个操作数的类型是Boolean
,则条件表达式的类型为boolean
。”
Integer.intValue()
也适用。不行,这与以下内容相同:
Integer test = null;
if ( test != null ) {
test = test.intValue();
}
else {
test = 0;
}