Short form for Java if statement

后端 未结 15 1392
半阙折子戏
半阙折子戏 2020-12-02 04:38

I know there is a way for writing a Java if statement in short form.

if (city.getName() != null) {
    name = city.getName();
} else {
    name=         


        
15条回答
  •  情深已故
    2020-12-02 05:19

    Use the ternary operator:

    name = ((city.getName() == null) ? "N/A" : city.getName());
    

    I think you have the conditions backwards - if it's null, you want the value to be "N/A".

    What if city is null? Your code *hits the bed in that case. I'd add another check:

    name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());
    

提交回复
热议问题