if-else-if Statement

Purpose:

To choose among alternate courses of action in a program.

Mechanics:

if (<condition 1>) {
/* Java statements (1) */
}
else if (<condition 2>) {
/* Java statements (2) */
}
else if (<condition n>) {
/* Java statments (n) */
}
[<else clause>]

Example:

if (numA == numB) {
/* Java statements (1) */
}
else if (numA > numB) {
/* Java statements (2) */
}
else if (numA < numB) {
/* Java statements (3) */
}

Usage:

  • <condition 1>, <condition 2>,..., <condition n> are expressions that evaluate to true or false.

Restrictions:

  • <condition1> is evaluated first. If it evaluates to true, then /* Java statements (1) */ are executed. The rest of the if-else-if construct is ignored. If <condition 1> is false, then <condition 2> is checked; if <condition 2> is false, <condition 3> is checked. This process continues until a condition evaluates to true. At this point, the statements following the associated if or else-if are executed. If none of the conditions evaluate to true, if there is a final else clause, those statements are executed. Otherwise, execution continues with the statements after the if-else-if construct.
  • If the clauses for any of the conditions is more than one statement, than curly brackets are necessary. Otherwise, the brackets are optional.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu