Search code examples
javaif-statementternary-operatorshort

Short form for Java If Else statement


I have a method which checks for nulls. Is there a way to reduce the number of lines in the method? Currently, the code looks "dirty":

private int similarityCount (String one, String two) {

    if (one == null && two == null) {
        return 1;
    } else if (one == null && two != null) {
        return 2;
    } else if (one != null && two == null) {
        return 3;
    } else {
        if(isMatch(one, two))
             return 4;
        return 5;
    }

}

Solution

  • private int similarityCount (String one, String two) {
    
        if (one == null && two == null) {
            return 1;
        } 
    
        if (one == null) {
            return 2;
        } 
    
        if (two == null) {
            return 3;
        } 
    
        if (isMatch(one, two)) {
            return 4;
        }
        return 5;
    }