if-else-if StatementPurpose:
- 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
trueorfalse.
Restrictions:
- <condition1> is evaluated first. If it evaluates
to
true, then/* Java statements (1) */are executed. The rest of theif-else-ifconstruct is ignored. If <condition 1> isfalse, then <condition 2> is checked; if <condition 2> isfalse, <condition 3> is checked. This process continues until a condition evaluates totrue. At this point, the statements following the associatediforelse-ifare executed. If none of the conditions evaluate totrue, if there is a finalelseclause, those statements are executed. Otherwise, execution continues with the statements after theif-else-ifconstruct. - If the clauses for any of the conditions is more than one statement, than curly brackets are necessary. Otherwise, the brackets are optional.
email suggestions to: cs015tas@cs.brown.edu
