Time for some refreshing the memory with a Java language feature probably few use, and maybe for a good reason. Suppose you’re running code on elements of an array up until a certain element is found. When your code finds that element, it stops the iteration. Therefore, your code might look like the following:
for (int i = 0; i < array.length && condition(array[i]); i++) {
// your code here
}
Or, if you’d like to use the new foreach feature, like this:
for (T item : array) {
if (condition(item)) {
break;
}
// your code here
}
Breaking out of the matrix
Okay, let’s now escalate this problem to a matrix. You are iterating a matrix (for the sake of example, it doesn’t matter to which direction) running code on its elements and would like to stop when a certain element was found. Your code might look like:
boolean found = false;
for (int x = 0; x < matrix.length && !found; x++) {
for (int y = 0; y < matrix[x].length && !found; y++) {
if (condition(matrix[x][y])) {
found = true;
} else {
// your code here
}
}
}
Now, because of the use of the && !found in the second part of the for loop, the foreach construct can’t be used! And also, to be honest, it’s kind of an ugly code. On the other hand, trying to use the break keyword like we did before is useless:
for (T[] column : matrix) {
for (T item : column) {
if (condition(item) {
break; // only breaks out of the second loop!
}
// your code here
}
}
Labels
And here’s where the old-yet-perhaps-unfamiliar feature comes into place: Labels. While not added to the Java language as it was in the C language, labels allow you to beak and continue when in nested scopes. That means nested if, nested for loops, and even nested random scopes, when you just open a scope for the sake of it. You can’t, however, assign a label to something that is not a scope.
Right, so knowing this about labels, let’s review the latest code:
mainLoop:
for (T[] column : matrix) {
for (T item : column) {
if (condition(item) {
break mainLoop; // breaks properly!
}
// your code here
}
}
And there you go!