5.4 Selection Using if/else if

The last form of an if statement is appropriate when the data falls into more than two mutually exclusive categories and the appropriate instructions to execute are different for each category. For this situation, Java provides the if/else if statement.

The if/else if statement follows this pattern:

if ( condition 1 )
{
      true block for condition 1
}
else if ( condition 2 )
{
      true block for condition 2
}
. . .
else if ( condition n )
{
      true block for condition n
}

else
{
      false block for all conditions being false
}
next statement

The flow of control for this form of the if statement is shown in Figure 5.8.

There can be any number of conditions in an if/else if statement. As we can see, once a condition evaluates ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.