Short form for Java if statement

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

    1. You can remove brackets and line breaks.

    if (city.getName() != null) name = city.getName(); else name = "N/A";
    

    2. You can use ?: operators in java.

    Syntax:

    Variable = Condition ? BlockTrue : BlockElse;
    

    So in your code you can do like this:

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

    3. Assign condition result for Boolean

    boolean hasName = city.getName() != null;
    

    EXTRA: for curious

    In some languages based in JAVA like Groovy, you can use this syntax:

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

    The operator ?: assign the value returned from the variable which we are asking for. In this case, the value of city.getName() if it's not null.

提交回复
热议问题