Short form for Java if statement

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

    here is one line code

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

    here is example how it work, run below code in js file and understand the result. This ("Data" != null) is condition as we do in normal if() and "Data" is statement when this condition became true. this " : " act as else and "N/A" is statement for else condition. Hope this help you to understand the logic.

    name = ("Data" != null) ? "Data" : "N/A";
    
    console.log(name);

提交回复
热议问题