Comp 110 else-if Syntax Trick

else-if Syntax

The else-if Syntax is a trick in Java that doesn't change the functionality of code, but it makes it a lot easier to look at and work with. For example, check out the code below:

if (testConditionA) {
    <code runs if test condition A is true>
} else {
    if (testConditionB) {
        <code runs if test condition B is true>
    } else {
        if (testConditionC) {
            <code runs if test condition C is true>
        } else {
            if (testConditionD) {
                <code runs if test condition D is true>
            } else {
                <code runs if test conditions A, B, C, and D are not true> 
            }
}        

Notice that this syntax looks a little messy. If you try and look at where the brackets open and close then you are going to have a bad time, and it makes diagnosing small syntax errors a chore. 

Now, imagine if we had a way to make it look a lot cleaner (see below).

if (testConditionA) {
    <code runs if test condition A is true>
} else if (testConditionB) {
    <code runs if test condition B is true>
} else if (testConditionC) {
    <code runs if test condition C is true>
} else if (testConditionD) {
    <code runs if test condition D is true>
} else {
    <code runs if test conditions A, B, C, and D are not true> 

This code looks different, but it is functionally the exact same as the first block of code. The trick is just to write if directly after the else, instead of opening new curly brackets for the else statement. For example:

if (aConditionA){
    <code runs if aConditionA is true>
} else {
    if (aConditionB) {
        <code runs if aConditionB is true>
    }

//the above code is the same as writing:

if (aConditionA){
    <code runs if aConditionA is true>
} else if (aConditionB) {
    <code runs if aConditionB is true>
}

In the end, it is all up to personal preference. However, the else-if trick is almost always the better way to make your code look cleaner and to ensure easy debugging. Each boolean test expression is evaluated until one evaluates to true. The rest are then skipped.