Java Reference
In-Depth Information
Table 4-4
The if...else Statement
General form:
1. if (condition) clause; //single result
2. if (condition)
{
clause 1;
clause 2;
} //used for multiple results
3. if (condition)
{
clause(s);
}
else
{
clause(s);
}
where condition is a relation that is evaluated to be boolean (either true or false) and clause
is a statement or series of statements; the else keyword and subsequent clause are optional.
Purpose:
To perform selection or make a decision on whether to execute a particular piece of code
based on the evaluation of a condition. The words, if and else , are reserved keywords. The
condition must evaluate to a boolean expression. If the condition is true, the clause or clauses
following the if statement execute. If the condition is false and an else clause is included, Java
executes the else clause. After either clause is executed, control passes to the statement
following the if statement in the first form (known as a single-line if statement) and to the
statement following the corresponding statement in the second and third forms. Either way,
execution passes out of the if statement to the next line of code following the statement.
Examples:
1. if (age > 65) seniorCount = seniorCount + 1;
2. if (tax >= 0)
{
code = "Y";
text = "Gross Pay";
}
3. if (marStatus == 1)
{
System.out.println("Married");
}
else
{
System.out.println("Single");
}
Each of the single-line if statements, block if statements, or if…else state-
ments may be nested , or completely included, within another if statement. For
example, in the if…else statement in Figure 4-12, the code in line 15 first tests if
the age is greater than 21. If that condition is evaluated as true, a second if state-
ment in line 17 is nested within the first if statement to test if the age is greater
than 64. Lines 17 through 26 are said to be nested within the block if statement
that begins in line 15.
 
Search WWH ::




Custom Search