三元运算符和意外的 NullPointerException
有时我会从下面一行收到 NullPointerException
。
System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");
添加括号后就可以了。
System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));
请澄清我的行为。提前致谢。
I am getting NullPointerException
from the below line sometimes.
System.out.println("Date::"+ row != null ? row.getLegMaturityDate() : "null");
After adding brackets, it is fine.
System.out.println("Date::"+ (row != null ? row.getLegMaturityDate() : "null"));
Please clarify me the behavior. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
"Date::" + row
永远不会为空,尽管row
有时是这样。也就是说,
"Date::"+ row != null
等价于("Date::"+ row) != null
,后者始终为 true。"Date::" + row
is never null, althoughrow
sometimes is.That is,
"Date::"+ row != null
is equivalent to("Date::"+ row) != null
which is always true.这是一个运算符优先级的问题。 Christoffer Hammarström 有执行摘要。请参阅此页面 http://bmanolov.free.fr/javaoperators.php 了解更多详细信息。
It's a matter of operator precedence. Christoffer Hammarström has the executive summary. See this page http://bmanolov.free.fr/javaoperators.php for more detail.