(^154) | Selection and Encapsulation
4.1 Flow of Control
The order in which statements execute is called the flow of control. In a sense, the
computer is under the control of one statement at a time. After a statement exe-
cutes, control turns over to the next statement (like a baton being passed in a re-
lay race).
The flow of control is normally sequential (see Figure 4.1). That is, when one
statement is finished executing, control passes to the next statement in the code.
Where we want the flow of control to be nonsequential, we use control structures,
or special statements that transfer control to a statement other than the one that
physically comes next. As we saw earlier, method calls are control structures that
alter the flow of control so that a separate sequence of statements can be executed.
Selection
We use a selection (or branching) control structure when we want the com-
puter to choose between alternative actions. To do so, we make an asser-
tion, a claim that is either true or false. If the assertion is true, the computer
executes one statement. If it is false, it executes another (see Figure 4.2). The
computer’s ability to solve practical problems is a product of its ability to
make decisions and execute different sequences of instructions.
The Payrollapplication in Chapter 3 is unable to recognize an invalid amount of hours
worked, such as a negative number. How can the computer respond to erroneous input? It
can decide whether a negative number has been entered. It does so by testing the assertion
that the number is less than zero. If the assertion is true, the computer follows the instruc-
tions for displaying an error message. If the assertion is false, the computer simply computes
the pay. Before we examine selection control structures in Java, let’s look closely at how we
get the computer to make decisions.
4.2 Conditions and Logical Expressions
To ask a question in Java, we don’t phrase it as a question; rather, we state it as an assertion.
If our assertion is true, the answer to the question is yes. If our assertion is false, the answer
to the question is no. The need to simplify assertions to true-false form stems from the fact
Flow of control The order in
which the computer executes
statements
Control structure A statement
used to alter the normally
sequential flow of control
statement 1
statement 2
statement 3
statement 4
Flow of
control
Figure 4.1 Sequential Control