Java Reference
In-Depth Information
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
Fig. 5.14
|
continue
statement terminating an iteration of a
for
statement. (Part 2 of 2.)
Figure 5.14 uses
continue
(line 10) to skip the statement at line 12 when the nested
if
determines that
count
's value is
5
. When the
continue
statement executes, program
control continues with the increment of the control variable in the
for
statement (line 7).
In Section 5.3, we stated that
while
could be used in most cases in place of
for
. This
is
not
true when the increment expression in the
while
follows a
continue
statement. In
this case, the increment does
not
execute before the program evaluates the repetition-con-
tinuation condition, so the
while
does not execute in the same manner as the
for
.
Software Engineering Observation 5.2
Some programmers feel that
break
and
continue
violate structured programming. Since the
same effects are achievable with structured programming techniques, these programmers do
not use
break
or
continue
.
Software Engineering Observation 5.3
There's a tension between achieving quality software engineering and achieving the best-
performing software. Sometimes one of these goals is achieved at the expense of the other.
For all but the most performance-intensive situations, apply the following rule of thumb:
First, make your code simple and correct; then make it fast and small, but only if necessary.
The
if
,
if
…
else
,
while
,
do
…
while
and
for
statements each require a
condition
to de-
termine how to continue a program's flow of control. So far, we've studied only simple
conditions, such as
count
<=
10
,
number != sentinelValue
and
total
>
1000
. Simple con-
ditions are expressed in terms of the relational operators
>
,
<
,
>=
and
<=
and the equality
operators
==
and
!=
, and each expression tests only one condition. To test
multiple
condi-
tions in the process of making a decision, we performed these tests in separate statements
or in nested
if
or
if
…
else
statements. Sometimes control statements require more com-
plex conditions to determine a program's flow of control.
Java's
logical operators
enable you to form more complex conditions by
combining
simple conditions. The logical operators are
&&
(conditional AND),
||
(conditional OR),
&
(boolean logical AND),
|
(boolean logical inclusive OR),
^
(boolean logical exclusive OR)
and
!
(logical NOT). [
Note:
The
&
,
|
and
^
operators are also bitwise operators when they're
applied to integral operands. We discuss the bitwise operators in online Appendix K.]
Conditional AND (
&&
) Operator
Suppose we wish to ensure at some point in a program that two conditions are
both
true
before we choose a certain path of execution. In this case, we can use the
&&
(
conditional
AND
) operator, as follows:
if
(gender ==
FEMALE
&& age >=
65
)
++seniorFemales;