Java Reference
In-Depth Information
describes the repetition during a shopping trip. The condition “there are more items on my
shopping list” may be true or false. If it's true , then the action “Purchase next item and cross
it off my list” is performed. This action will be performed repeatedly while the condition re-
mains true . The statement(s) contained in the While repetition statement constitute its body,
which may be a single statement or a block. Eventually, the condition will become false
(when the shopping list's last item has been purchased and crossed off). At this point, the
repetition terminates, and the first statement after the repetition statement executes.
As an example of Java's while repetition statement , consider a program segment that
finds the first power of 3 larger than 100. Suppose that the int variable product is initial-
ized to 3 . After the following while statement executes, product contains the result:
while (product <= 100 )
product = 3 * product;
Each iteration of the while statement multiplies product by 3, so product takes on the
values 9, 27, 81 and 243 successively. When product becomes 243, product <= 100 be-
comes false. This terminates the repetition, so the final value of product is 243. At this
point, program execution continues with the next statement after the while statement.
Common Programming Error 4.2
Not providing in the body of a while statement an action that eventually causes the con-
dition in the while to become false normally results in a logic error called an infinite loop
(the loop never terminates).
UML Activity Diagram for a while Statement
The UML activity diagram in Fig. 4.6 illustrates the flow of control in the preceding
while statement. Once again, the symbols in the diagram (besides the initial state, transi-
tion arrows, a final state and three notes) represent an action state and a decision. This di-
agram introduces the UML's merge symbol . The UML represents both the merge symbol
and the decision symbol as diamonds. The merge symbol joins two flows of activity into
one. In this diagram, the merge symbol joins the transitions from the initial state and from
the action state, so they both flow into the decision that determines whether the loop
should begin (or continue) executing.
merge
decision
[product <= 100]
triple product value
[product > 100]
Corresponding Java statement:
product = 3 * product;
Fig. 4.6 | while repetition statement UML activity diagram.
 
 
Search WWH ::




Custom Search