本文介绍了为什么三元运算给出了nullpointer,而ifelse对应的呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的一个实例中得到NullPointerException,而它的对应物运行顺畅。

I am getting NullPointerException in one instance below while its counterpart runs smooth.

public static void main(String[] args){
    System.out.println(withTernary(null, null)); //Null Pointer
    System.out.println(withIfElse(null, null));  //No Exception
}

private static Boolean withTernary(String val, Boolean defVal){
    return val == null ? defVal : "true".equalsIgnoreCase(val);
}

private static Boolean withIfElse(String val, Boolean defVal){
    if (val == null) return defVal;
    else return "true".equalsIgnoreCase(val);
}

,从 withIfElse 输出 null ,然后在<$中失败c $ c> withTernary 。

我正在使用以下java版本

I am using following java version

java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609)
Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)


推荐答案

以下是:

布尔条件表达式的类型确定如下:

The type of a boolean conditional expression is determined as follows:


  • 如果第二个第三个操作数都是 Boolean 类型,条件表达式的类型为 Boolean

  • If the second and third operands are both of type Boolean, the conditional expression has type Boolean.

否则,条件表达式的类型为 boolean

Otherwise, the conditional expression has type boolean.

因此,整个表达式的类型被认为是 boolean ,以及 Boolean 值是自动装箱的,导致 NullPointerException

Therefore, the overall expression's type is considered to be boolean, and the Boolean value is autounboxed, causing a NullPointerException.

如评论中所述,为什么以下不会引发异常?

As mentioned in the comments, why doesn't the following raise an exception?

return val == null ? null : "true".equalsIgnoreCase(val);

嗯,上面的规范摘录特别适用于布尔条件表达式,指定:

Well, the above excerpt from the spec specifically only applies to boolean conditional expressions, which are specified here (§15.25):

为了对条件进行分类,以下表达式是布尔表达式:

For the purpose of classifying a conditional, the following expressions are boolean expressions:


  • 独立表单的表达式()类型为 boolean Boolean

带括号的布尔表达式()。

类实例创建表达式()类布尔

A class instance creation expression (§15.9) for class Boolean.

方法调用表达式()选择最具体的方法()返回类型 boolean Boolean

(注意,对于泛型方法,这是在实例化方法的类型参数之前的类型。)

A method invocation expression (§15.12) for which the chosen most specific method (§15.12.2.5) has return type boolean or Boolean.
(Note that, for a generic method, this is the type before instantiating the method's type arguments.)

A 布尔条件表达式。

由于 null 不是布尔表达式,整体条件表达式不是布尔值条件表达式。参考表15.2(稍后在同一节中),我们可以看到这样的表达式被认为具有 Boolean 类型,因此不会发生拆箱,也不会引发异常。

Since null is not a boolean expression, the overall conditional expression is not a boolean conditional expression. Referring to Table 15.2 (later in the same section), we can see that such an expression is considered to have a Boolean type, so no unboxing occurs, and no exception is raised.

这篇关于为什么三元运算给出了nullpointer,而ifelse对应的呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 00:49