Java Reference
In-Depth Information
You have already seen the use of the unlabeled
break
statement inside
switch
,
for
-loop,
while
-loop, and
do-while
statements. It transfers control out of a
switch
,
for
-loop,
while
-loop, and
do-while
statement in which it
appears. In case of nested statements of these four kinds, if an unlabeled
break
statement is used inside the inner
statement, it transfers control only out of the inner statement, not out of the outer statement. Suppose you want to
print the lower half of the 3x3 matrix as shown:
11 21 22
31 32 33
To print only the lower half of the 3x3 matrix, you can write the following snippet of code:
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print ( i + "" + j);
if (i == j) {
break; // Exit the inner for loop
}
System.out.print("\t");
}
System.out.println();
}
The
break
statement has been used inside the inner
for
-loop statement. When the value of the outer loop
counter (
i
) becomes equal to the value of the inner loop counter (
j
), the
break
statement is executed, and the inner
loop exits. If you want to exit from the outer
for
-loop statement from inside the inner
for
-loop statement, you have to
use a labeled
break
statement. A label in Java is any valid Java identifier followed by a colon. The following are some
valid labels in Java:
label1:
alabel:
Outer:
Hello:
IamALabel:
Now use a labeled
break
statement in the above example and see the result.
outer: // Defines a label named outer
for(int i = 1; i <= 3; i++ ) {
for(int j = 1; j <= 3; j++ ) {
System.out.print(i + "" + j);
if (i == j) {
break outer; // Exit the outer for loop
}
System.out.print("\t");
}
System.out.println();
} // The outer label ends here