Short form for Java if statement

后端 未结 15 1449
半阙折子戏
半阙折子戏 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:06

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

    firstly the condition (city.getName() == null) is checked. If yes, then "N/A" is assigned to name or simply name="N/A" or else the value from city.getName() is assigned to name, i.e. name=city.getName().

    Things to look out here:

    1. condition is in the parenthesis followed by a question mark. That's why I write (city.getName() == null)?. Here the question mark is right after the condition. Easy to see/read/guess even!
    2. value left of colon (:) and value right of colon (a) value left of colon is assigned when condition is true, else the value right of colon is assigned to the variable.

    here's a reference: http://www.cafeaulait.org/course/week2/43.html

提交回复
热议问题