Java Selection Statements: if-else-if Statements
As we have seen, an if-else statement provides executable codes blocks for both a true contrition and a false condition. But what if your program needs more options? Something that can handle more that a simple true or false outcome.
The if-else-if statement, or the extended if-else statement, allows the evaluation of multiple conditions. The if statements are executed from the top down and as soon as one of the conditions evaluates to true, the corresponding code block is executed and any remaining if statements are ignored. If none of the conditions evaluate to true, then the final else statement will be executed. The general syntax is:
if (condition) {
statement;
} else if (condition) {
statement;
//continue with as many else if (condition) as required
} else {
statement;
}
Let’s see how this might work in practice. Let’s write a program for an apartment block that will output a suitable message to the resident depending on the which apartment number was pressed. There are 5 apartments in the block but only 3 are occupied (apartment 01, 02 and 05), so we only need to output personalised messages for those 3 and the unoccupied apartments will be directed to the caretakers location with a suitable message.
int buzzerPressed = 05; if(buzzerPressed == 01) { System.out.println("James Smith, you have a visitor."); } else if (buzzerPressed == 02) { System.out.println("Bob Jones, you have a visitor."); } else if (buzzerPressed == 05) { System.out.println("Helen Green, you have a visitor."); } else { System.out.println("Caretaker, you have a visitor."); }
Here, the buzzer pressed (the variable buzzerPressed) was for apartment 05 and the program evaluated each if statement in turn until it found that buzzerPressed == 05. When you execute this code you should see an output of:
run: Helen Green, you have a visitor. BUILD SUCCESSFUL (total time: 0 seconds)
Try changing the value of buzzerPressed to see if you get the outcomes that you expect. Notice there is nobody living in apartments 03 and 04 and there are no if statements for those numbers, what happens if either one of those buzzers are pressed? Is this where the else statement comes in?