Java Reference
In-Depth Information
The break Statement
A
break
statement causes the Java interpreter to skip immediately to the end of a
containing statement. We have already seen the
break
statement used with the
switch
statement. The
break
statement is most often written as simply the keyword
break
followed by a semicolon:
break
;
When used in this form, it causes the Java interpreter to immediately exit the inner‐
most containing
while
,
do
,
for
, or
switch
statement. For example:
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++)
{
if
(
data
[
i
]
==
target
)
{
// When we find what we're looking for,
index
=
i
;
// remember where we found it
break
;
// and stop looking!
}
}
// The Java interpreter goes here after executing break
The
break
statement can also be followed by the name of a containing labeled state‐
ment. When used in this form,
break
causes the Java interpreter to immediately exit
the named block, which can be any kind of statement, not just a loop or
switch
. For
example:
TESTFORNULL:
if
(
data
!=
null
)
{
for
(
int
row
=
0
;
row
<
numrows
;
row
++)
{
for
(
int
col
=
0
;
col
<
numcols
;
col
++)
{
if
(
data
[
row
][
col
]
==
null
)
break
TESTFORNULL
;
// treat the array as undefined.
}
}
}
// Java interpreter goes here after executing break TESTFORNULL
The continue Statement
While a
break
statement exits a loop, a
continue
statement quits the current itera‐
tion of a loop and starts the next one.
continue
, in both its unlabeled and labeled
forms, can be used only within a
while
,
do
, or
for
loop. When used without a label,
continue
causes the innermost loop to start a new iteration. When used with a label
that is the name of a containing loop, it causes the named loop to start a new itera‐
tion. For example:
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++)
{
// Loop through data.
if
(
data
[
i
]
==
-
1
)
// If a data value is missing,
continue
;
// skip to the next iteration.
process
(
data
[
i
]);
// Process the data value.
}
while
,
do
, and
for
loops differ slightly in the way that
continue
starts a new
iteration: