【问题标题】:Ternary Operator and unexpected NullPointerException三元运算符和意外的 NullPointerException
【发布时间】:2011-12-31 08:57:51
【问题描述】:

我有时会从下面的行中收到NullPointerException。

System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");

加上括号后就好了。

System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));

请澄清我的行为。提前致谢。

【问题讨论】:

  • 这就是为什么我尽量限制嵌套语句/表达式。如果您将语句一分为二,就不会有这个问题。

标签: java ternary-operator


【解决方案1】:

"Date::" + row 永远不会为空,尽管row 有时是。

也就是说,"Date::"+ row != null 等价于 ("Date::"+ row) != null,这始终是正确的。

【讨论】:

【解决方案2】:

这是运算符优先级的问题。 Christoffer Hammarström 有执行摘要。有关详细信息,请参阅此页面http://bmanolov.free.fr/javaoperators.php。

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多