Short form for Java if statement

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

    I'm always forgeting how to use the ?: ternary operator. This supplemental answer is a quick reminder. It is shorthand for if-then-else.

    myVariable = (testCondition) ? someValue : anotherValue;
    

    where

    • () holds the if
    • ? means then
    • : means else

    It is the same as

    if (testCondition) {
        myVariable = someValue;
    } else {
        myVariable = anotherValue;
    }
    

提交回复
热议问题