代码之家  ›  专栏  ›  技术社区  ›  Mike Pone

Java三元(即时if)评估

  •  24
  • Mike Pone  · 技术社区  · 15 年前

    我找不到规范的相关部分来回答这个问题。 在Java中的条件运算符语句中,是否同时计算true和false参数?

    那么下面的代码是否会抛出NullPointerException呢

    Integer test = null;
    
    test != null ? test.intValue() : 0;
    
    3 回复  |  直到 11 年前
        1
  •  60
  •   Pang waqas ur Rehman    12 年前

    既然你想要规格,就在这里(从 §15.25 Conditional Operator ? : ,本节最后一句):

        2
  •  24
  •   randers    9 年前

    我知道这是一篇老文章,但看看非常相似的案例,然后给我投票:P

    回答原始问题:只计算一个操作数,但:

    @Test
    public void test()
    {
        Integer A = null;
        Integer B = null;
    
        Integer chosenInteger = A != null ? A.intValue() : B;    
    }
    

    这项测试将抛出 NullPointerException 始终,在这种情况下,如果statemat不等于?:运算符。

    原因就在这里 http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.25 . 有关装箱/拆箱的部分涉及其中,但很容易理解:

    “如果第二个和第三个操作数之一的类型为 boolean 另一种类型是 Boolean ,则条件表达式的类型为 布尔值 ."

    这同样适用于 Integer.intValue()

    顺致敬意,

        3
  •  9
  •   stevedbrown    15 年前

    不,不可能。这与:

    Integer test = null;
    if ( test != null ) { 
        test = test.intValue();
    }
    else {
        test = 0;
    }