Ternary Operator and unexpected NullPointerException

倾然丶 夕夏残阳落幕 提交于 2019-12-01 17:09:50

问题


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.


回答1:


"Date::" + row is never null, although row sometimes is.

That is, "Date::"+ row != null is equivalent to ("Date::"+ row) != null which is always true.




回答2:


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.



来源:https://stackoverflow.com/questions/8168130/ternary-operator-and-unexpected-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!