我有时会从下面的行中获取NullPointerException
。三元运算符和意外的空指针异常
System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");
添加括号后,没事的。
System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));
请说清楚我的行为。提前致谢。
我有时会从下面的行中获取NullPointerException
。三元运算符和意外的空指针异常
System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");
添加括号后,没事的。
System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));
请说清楚我的行为。提前致谢。
"Date::" + row
从不为空,尽管row
有时是。
也就是说,"Date::"+ row != null
相当于("Date::"+ row) != null
这总是正确的。
要添加到此,你应该看看http://stackoverflow.com/questions/2137690/java-operator-precedence-guidelines –
谢谢克里斯托弗。得到它了。 @Mike,感谢您的链接,内容翔实。 – Vaandu
这是一个运算符优先级的问题。 Christoffer Hammarström有执行摘要。请参阅此页面http://bmanolov.free.fr/javaoperators.php了解更多详情。
这就是为什么我尽量限制嵌套语句/表达式的原因。如果你想将陈述分成两份,你就不会有这个问题。 – helpermethod