Using the OR operator inside an if or just else if?

Good morning/afternoon/night,

I'm writting a simple function which will return a boolean if the string given as an argument (in this case a two character code) is matched.

I was wondering which would be considered the "Best" way to go about this, would it be using a number of || operators within a single if like below:

private boolean isCodeSpecial(String code){
    if( code.equalsIgnoreCase("AA") ||
        code.equalsIgnoreCase("AB") ||
        code.equalsIgnoreCase("SS") ||
        code.equalsIgnoreCase("DD") ||
        code.equalsIgnoreCase("YY") ||
        code.equalsIgnoreCase("ZZ") ||
        code.equalsIgnoreCase("AX") ){
        return true;
    }
    return false;
}

Or perhaps using a series of else if statements like the below:

private boolean isCodeSpecial(String code){
    if(code.equalsIgnoreCase("AA")){
        return true;
    }else if(code.equalsIgnoreCase("AB")){
        return true;
    }else if(code.equalsIgnoreCase("SS")){
    return true;
    }else if(code.equalsIgnoreCase("DD")){
        return true;
    }else if(code.equalsIgnoreCase("YY")){
        return true;
    }else if(code.equalsIgnoreCase("ZZ")){
        return true;
    }else if(code.equalsIgnoreCase("AX")){
        return true;
    }else{
        return false;
    }
}

I'm not really concerned about performance in this application, as I know any gains/penalies will likely be minimal and almost unnoticable - but if possible I would like to know whats generally considered best practice for future reference. I guess the argument could be made that this is exactly what else if is for ?

Thanks in advance,

Edit: Forgot to mention that I am using Java 1.6 (so I dont beleive a simple switch is possible without the use of Enums ?)

Jon Skeet
people
quotationmark

Why use an if statement at all?

return code.equalsIgnoreCase("AA") ||
    code.equalsIgnoreCase("AB") ||
    code.equalsIgnoreCase("SS") ||
    code.equalsIgnoreCase("DD") ||
    code.equalsIgnoreCase("YY") ||
    code.equalsIgnoreCase("ZZ") ||
    code.equalsIgnoreCase("AX");

If you really want the if statements, then I'd definitely go with the first approach. It will perform exactly the same number of comparisons as the if/else/if/else code due to shortcircuiting - if the first operand of the || operator evaluates to true, then the second operand won't be evaluated... but it's a lot clearer.

Another alternative would be to create a fixed case-insensitive set so you could then say:

return VALID_CODES.contains(code);

You could do that with a TreeSet:

private static final Set<String> VALID_CODES =
    new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

static {
    VALID_CODES.add("AA");
    VALID_CODES.add("AB");
    VALID_CODES.add("SS");
    VALID_CODES.add("DD");
    VALID_CODES.add("YY");
    VALID_CODES.add("ZZ");
    VALID_CODES.add("AX");
}

people

See more on this question at Stackoverflow