Conditional Operator with and without ()

限于喜欢 提交于 2019-12-25 07:49:25

问题


I have run in to some weird thing when I want to print one of my objects (which is obviously not null).

If I use this line:

text.append("\n [ITEM ID]: " + (item == null ? (otherItem == null ? 0 : otherItem .getItems().get(i).getId()) : item .getItems().get(i).getId()));

There is no null pointer exception if my item object is null. Of course this should be the excepted result. But if I use it without the () marks:

text.append("\n [ITEM ID]: " + item == null ? (otherItem == null ? 0 : otherItem .getItems().get(i).getId()) : item .getItems().get(i).getId())

I thought the conditional operator does not execute the other part of the operator, but I got a NullPointerException.

I would appreciate if someone explain it to me, why it is essential to use the () marks in this case.


回答1:


The concatenation between "\n [ITEM ID]: " and item will have priority on the equality test and the conditional operator if you don't put the parenthesis (see the precedences in Java operators), so you have to put them if you want it to work (as ("\n [ITEM ID]: " + item) == null is probably not what you want to evaluate).




回答2:


The + operator has higher precedence than ? :, so you do need to use parenthesis. See http://bmanolov.free.fr/javaoperators.php



来源:https://stackoverflow.com/questions/9331283/conditional-operator-with-and-without

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