Java Reference
In-Depth Information
The output of the above snippet of code will be 11. Why did it print only one element of the 3x3 matrix? This time
you have used a labeled
break
statement inside the inner
for
-loop statement. When
i == j
evaluates to
true
for
the first time, the labeled
break
statement is executed. It transfers control out of the block, which has been labeled
as
outer
. Note that the
outer
label appears just before the outer
for
-loop statement. Therefore, the block associated
with the label
outer
is the outer
for
-loop statement. A labeled statement can be used not only inside
switch
,
for
-loop,
while
-loop, and
do-while
statements. Rather it can be used with any type of a block statement. The
following is a trivial example of a labeled
break
Statements:
blockLabel:
{
int i = 10;
if (i == 5) {
break blockLabel; // Exits the block
}
if (i == 10) {
System.out.println("i is not five");
}
}
One important point to remember about a labeled
break
statement is that the label used with the
break
statement must be the label for the block in which that labeled
break
statement is used. The following snippet of code
illustrates an incorrect use of a labeled
break
Statements:
lab1:
{
int i = 10;
if (i == 10)
break lab1; // Ok. lab1 can be used here
}
lab2:
{
int i = 10;
if (i == 10)
// A compile-time error. lab1 cannot be used here because this block is not
// associated with lab1 label. We can use only lab2 in this block
break lab1;
}
The continue Statement
A
continue
statement can only be used inside the
for
-loop,
while
-loop, and
do-while
statements. There are two
forms of the
continue
Statements:
Unlabeled
•
continue
statement
•
Labeled
continue
statement