Java Reference
In-Depth Information
Selection: if and if...else
Although there are only two logical values, true and false , they are extremely useful
because they permit programs to incorporate decision making that alters the processing
flow. The remainder of this chapter discusses ways to incorporate decisions into a
program. Java has three selection or branch control structures: if and if ... else
statements, and the switch structure. This section discusses how if and if ... else
statements can be used to create one-way selection, two-way selection, and multiple
selections. The switch structure is discussed later in this chapter.
One-Way Selection
A bank wants to send a notice to a customer if her or his checking account balance falls below
the required minimum balance. That is, if the balance is below the required minimum, the
bank should send a notice to the customer; otherwise, it should do nothing.Similarly,ifthe
policyholder of an insurance policy is a nonsmoker, the company wants to apply a 10% discount
to the policy premium. Both of these examples involve one-way selection. In Java, one-way
selections are incorporated using the if statement. The syntax of one-way selection is:
if (logical expression)
statement
Note the elements of this syntax. It begins with the reserved word if , followed by a
logical expression contained within parentheses, followed by a statement . The
logical expression is also called a condition; it decides whether to execute the
statement that follows it. If logical expression is true , the statement executes. If
it is false , the statement does not execute and the computer goes on to the next
statement in the program. The statement following the logical expression is
sometimes called the action statement. (Note the indentation of the action statement .
We have indented it four spaces to the right of the if statement in the previous line.)
Figure 4-2 shows the flow of execution of the if statement (one-way selection).
logical expression
true
statement
false
FIGURE 4-2 One-way selection
 
Search WWH ::




Custom Search