CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING
Listing 5-16. Labeled break statement
String[][] pieces = {
{"Black Castle", "Black Knight", "Black Bishop", "Black Queen",
"Black King", "", "", ""},
{"Black Pawn", "Black Pawn", "Black Pawn", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"White Pawn", "White Pawn", "White Pawn", "", "", "", "", ""},
{"White Castle", "White Knight", "White Bishop", "White Queen",
"White King", "", "", ""}
};
int x = 0, y = 0;
king:
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (pieces[i][j].equals("Black King")) {
x = i;
y = j;
break king;
}
}
}
System.out.println("x: " + x + ", y: " + y);
The king: label indicates which loop the break king; statement should terminate. Code execution
then resumes with the print statement below the outer loop.
The continue Statement
The continue statement works within loops. It stops the current iteration of the loop and moves to the
next one. The break statement, on the other hand, exits the entire loop. In other words, the continue
statement continues the loop, whereas the break statement breaks out of the loop (which explains the
origin of these two keywords). The general idiom for its use is that the code in the loop has determined
that it does not need to go further and can jump to processing the next item. It's Java's way of letting you
say, “No, not that one. How about the next one?” Returning to our chessboard, suppose we want to
count the number of surviving pawns (see Listing 5-17).
Listing 5-17. continue statement
String[][] pieces = {
{"Black Castle", "Black Knight", "Black Bishop", "Black Queen", "Black King", "", "", ""},
{"Black Pawn", "Black Pawn", "Black Pawn", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"", "", "", "", "", "", "", ""},
{"White Pawn", "White Pawn", "White Pawn", "", "", "", "", ""},
{"White Castle", "White Knight", "White Bishop", "White Queen", "White King", "", "", ""}