Sometimes there are several alternative actions, only one of which should be performed, depending on a set of conditions.
For example, a program might print out different greetings depending on the time of day.
int hour = aClock.getHour(); // getHour returns 0 - 24 Greeter host = new Greeter(); if ( hour < 12 ) { host.sayThis("Good morning."); } else if ( hour < 17 ) { host.sayThis("Good afternoon."); } else if ( hour < 20 ) { host.sayThis("Good evening."); } else { host.sayThis("Good night."); } host.sayThis("Welcome to the FormalGreetings Restaurant."); // Follow-up code goes here.Syntax:
- The boolean expressions (conditions to check) are always in parentheses.
- A boolean expression is provided only for an
if
.- There can be any number of
else if ( <boolean-expression> )
segments.- The final
else
does not have a boolean expression provided. (Similarly, in a simpleif/else
statement, theelse
statement does not include a boolean expression;else
means "in all other conditions".