Java Reference
In-Depth Information
If student's grade is greater than or equal to 60
Print “Passed”
determines whether the
condition
“student's grade is greater than or equal to 60” is
true
. If
so, “Passed” is printed, and the next pseudocode statement in order is “performed.” (Re-
member, pseudocode is not a real programming language.) If the condition is
false
, the
Print
statement is ignored, and the next pseudocode statement in order is performed. The
indentation of the second line of this selection statement is optional, but recommended,
because it emphasizes the inherent structure of structured programs.
The preceding pseudocode
If
statement may be written in Java as
if
(studentGrade >=
60
)
System.out.println(
"Passed"
);
The Java code corresponds closely to the pseudocode. This is one of the properties of
pseudocode that makes it such a useful program development tool.
UML Activity Diagram for an
if
Statement
Figure 4.2 illustrates the single-selection
if
statement. This figure contains the most im-
portant symbol in an activity diagram—the
diamond
, or
decision symbol
, which indicates
that a
decision
is to be made. The workflow continues along a path determined by the sym-
bol's associated
guard conditions
, which can be
true
or
false
. Each transition arrow emerg-
ing from a decision symbol has a guard condition (specified in
square brackets
next to the
arrow). If a guard condition is
true
, the workflow enters the action state to which the tran-
sition arrow points. In Fig. 4.2, if the grade is greater than or equal to 60, the program
prints “Passed,” then transitions to the activity's final state. If the grade is less than 60, the
program immediately transitions to the final state without displaying a message.
[grade >= 60]
print “Passed”
[grade < 60]
Fig. 4.2
|
if
single-selection statement UML activity diagram.
The
if
statement is a single-entry/single-exit control statement. We'll see that the
activity diagrams for the remaining control statements also contain initial states, transition
arrows, action states that indicate actions to perform, decision symbols (with associated
guard conditions) that indicate decisions to be made, and final states.
The
if
single-selection statement performs an indicated action only when the condition
is
true
; otherwise, the action is skipped. The
if
…
else
double-selection statement
allows
you to specify an action to perform when the condition is
true
and another action when
the condition is
false
. For example, the pseudocode statement