Java Reference
In-Depth Information
This statement represents a one-way selection. Because there is a semicolon at the end
of the logical expression in Line 1, the if statement terminates at Line 1, the action of
the if statement is null, and the statement in Line 2 is not part of the if statement.
The statement in Line 2 executes regardless of how the if statement evaluates. Note that
the semicolon in Line 1 is a logical error and this can be hard to debug. So be careful
when forming one-way selection.
Two-Way Selection
In the previous section, you learned how to implement one-way selections in a program.
There are many situations in which you must choose between two alternatives.
For example, if a part-time employee works overtime, the paycheck is calculated
using the overtime payment formula; otherwise, the paycheck is calculated using the
regular formula. This is an example of two-way selection. To choose between two
alternatives—that is, to implement two-way selections—Java provides the if ... else
statement. Two-way selection uses the following syntax:
4
if (logical expression)
statement1
else
statement2
Takeamomenttoexaminethissyntax.Itbeginswiththereservedword if ,followedbya
logical expression contained within parentheses, followed by a statement, followed by the
reserved word else , followed by a second statement. Statements 1 and 2 can be any valid Java
statements. In a two-way selection, if the value of the logical expression is true ,then
statement1 executes. If the value of the logical expression is false ,then statement2
executes. Figure 4-4 shows the flow of execution of the if ... else statement (two-way selection).
false
logical expression
true
statement1
statement2
FIGURE 4-4 Two-way selection
 
Search WWH ::




Custom Search