简体   繁体   中英

Conditional Operator with and without ()

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.

如果您不加上括号(请参阅Java运算符中的优先级 ),则"\\n [ITEM ID]: "item之间的连接将在相等性测试和条件运算符上具有优先级(请参阅Java运算符中的优先级 ),因此,如果需要希望它能正常工作(因为("\\n [ITEM ID]: " + item) == null可能不是您要评估的值)。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM