Short form for Java if statement

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

    You can write if, else if, else statements in short form. For example:

    Boolean isCapital = city.isCapital(); //Object Boolean (not boolean)
    String isCapitalName = isCapital == null ? "" : isCapital ? "Capital" : "City";      
    

    This is short form of:

    Boolean isCapital = city.isCapital();
    String isCapitalName;
    if(isCapital == null) {
        isCapitalName = "";
    } else if(isCapital) {
        isCapitalName = "Capital";
    } else {
        isCapitalName = "City";
    }
    
    0 讨论(0)
  • 2020-12-02 05:18

    Simple & clear:

    String manType = hasMoney() ? "rich" : "poor";
    

    long version:

          String manType;
        if (hasMoney()) {
            manType = "rich";
        } else {
            manType = "poor";
        }
    

    or how I'm using it to be clear for other code readers:

     String manType = "poor";
        if (hasMoney())
            manType = "rich";
    
    0 讨论(0)
  • 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());
    
    0 讨论(0)
提交回复
热议问题