Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Find the first pair (i, j) with grid[i][j] == target and stop both loops. Show a labeled break, then explain when extracting a method is better.

We put a label on the outer loop, outer:, and when we find the target we write break outer;, which leaves the labeled loop entirely, not just the inner one. The labeled form of continue, continue outer;, skips to the next iteration of the labeled loop instead. In most real code, though, extracting the search into a method that returns the pair on the first match is clearer, because return stops both loops naturally and there is no mutable result variable to manage.

Why this question is asked

Searching a two-dimensional grid and stopping at the first match is a small problem with a surprising number of wrong answers: a plain break that only leaves the inner loop, a boolean flag checked in both loop conditions, or a loop that keeps running after the answer is found. Interviewers ask it to see whether we know Java's labeled break, and, just as importantly, whether we know when not to use it. In this answer, we will see why a plain break is not enough, write the labeled version, explain labeled continue and where labels are allowed, and then refactor the search into a method and compare the two.

1Why a Plain break Is Not Enough

A break without a label leaves the innermost loop or switch that contains it, and nothing more. In a nested loop, that means it stops the inner loop over j, and the outer loop simply moves on to the next row. If the target appears again in a later row, our result is overwritten, and even if it does not, we waste time scanning every remaining row.

Java
int[][] grid = { {1, 2, 3}, {4, 7, 6}, {7, 8, 9} };
int target = 7;
int[] found = null;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == target) {
found = new int[] {i, j};
break; // leaves only the inner loop
}
}
}
System.out.println(Arrays.toString(found)); // [2, 0], but the first match was [1, 1]

Notice the result. The first 7 is at row 1, column 1, but the outer loop kept going, found the 7 at row 2, column 0, and overwrote the answer. The bug is easy to miss because the code does find a 7.

2Stopping Both Loops With a Labeled break

Java lets us put a label, an identifier followed by a colon, in front of a statement. Then break with that label leaves the labeled statement, however deeply we are nested inside it. So we label the outer loop and break out of it.

Java
int[] found = null;
outer:
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == target) {
found = new int[] {i, j};
break outer; // leaves both loops at once
}
}
}
System.out.println(Arrays.toString(found)); // [1, 1]
// found stays null if the target is not in the grid
Step throughHow break outer leaves the grid search
  1. outer: start row i
  2. Inner loop: check grid[i][j]
  3. Is grid[i][j] == target?
    YesRecord [i, j] and break outerNoNext j, or next row when the row ends
  4. First statement after the outer loopfound is [1, 1], or null if no match

4 steps in order. Play them, or step through them one at a time.

A labeled break leaves the labeled statement and every loop inside it.

Notice that break outer does not jump back to the label. It jumps to the first statement after the labeled loop, here the println. This is not a goto: a labeled break can only leave a statement that encloses it, so control flow still runs forwards and out, never into the middle of other code. Also notice that grid[i].length handles jagged arrays, where rows have different lengths.

3Labeled continue and Where Labels Are Allowed

continue without a label skips to the next iteration of the innermost loop. With a label, continue outer skips the rest of the current outer iteration and starts the next one. A typical use is skipping a whole row as soon as one of its values disqualifies it.

Java
int validRows = 0;
rows:
for (int[] row : grid) {
for (int v : row) {
if (v < 0) continue rows; // abandon this row, go to the next one
}
validRows++; // only reached when no value was negative
}
// grid with no negatives: validRows is 3

Formally, a label can be placed on any statement, even a block or an if, and break label works on any labeled statement that encloses it. But continue label only makes sense for a loop, and the compiler rejects it otherwise. In practice labels are only useful on loops and occasionally on a block, and putting one on anything else just confuses readers.

4Extracting a Method Instead

The labeled break works, but it has two weaknesses. The result lives in a mutable variable declared before the loops, and the reader has to find the label to know where control goes. Extracting the search into its own method removes both. return leaves the method, and therefore both loops, the moment we find a match, and the result is simply the return value.

Java
static Optional<int[]> findFirst(int[][] grid, int target) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == target) return Optional.of(new int[] {i, j});
}
}
return Optional.empty();
}
findFirst(grid, 7).map(Arrays::toString).orElse("none"); // [1, 1]
findFirst(grid, 42).map(Arrays::toString).orElse("none"); // none

Notice what changed. There is no label and no flag, the method name says what the loops do, and Optional makes the not-found case explicit instead of a null the caller might forget. A small record such as record Cell(int row, int col) would be even clearer than an int array. So our default is the method, and we keep labeled break for cases where extraction is awkward, for example when the loops update several local variables that the code after them needs, or in tight, performance-sensitive code where we want everything in one place.

5Follow-up questions

Is a labeled break the same as goto?

No. goto is a reserved word in Java that does nothing, so we cannot jump anywhere we like. A labeled break can only exit a statement that encloses it, and a labeled continue can only restart an enclosing loop, so control flow stays structured and easy to follow.

Could we use a boolean flag instead?

Yes, by adding && !done to both loop conditions, but it spreads the stopping logic over several places, and forgetting the check in one loop brings back the bug. A labeled break or an extracted method says the same thing in one place.

Could streams solve this?

IntStream.range(0, grid.length).boxed().flatMap(i -> IntStream.range(0, grid[i].length).filter(j -> grid[i][j] == target).mapToObj(j -> new int[] {i, j})).findFirst() works and is lazy, so it stops at the first match. For a simple search, most teams find the plain method easier to read.

6Conclusion

In this answer, we saw that a plain break only leaves the inner loop, which lets the search continue and overwrite the first match. A label on the outer loop and break outer leave both loops at once, and continue outer skips to the next outer iteration. Labels can be put on any statement but are only useful on loops and blocks. Extracting the search into a method that returns on the first match is usually clearer, because return ends both loops and there is no mutable result to manage.

What to say in the interviewAbout 80 seconds aloud

Open with

A plain break only leaves the inner loop, so the outer loop would keep scanning and could overwrite the first match. To stop both, I label the outer loop, write outer: in front of it, and when grid[i][j] equals the target I store the pair and write break outer.

Then, if they want more

That leaves the labeled loop entirely and continues with the first statement after it. It is not a goto, because it can only exit a statement that encloses it. The companion is continue outer, which abandons the current outer iteration and starts the next one, for example to skip a row as soon as one value disqualifies it.

Labels can technically go on any statement, but they are only really useful on loops and sometimes blocks.

That said, in most code I would extract the search into a method, something like findFirst(grid, target), and return as soon as I find a match. return exits both loops naturally, there is no mutable variable declared before the loops, the method name explains the intent, and I can return an Optional or a small record so the not-found case is explicit. I keep labeled break for cases where extracting a method would be awkward.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the first pair (i, j) with grid[i][j] == target and stop both loops. Show a labeled...": https://scrivio-interview-library.netlify.app/java/operators-and-control-flow/0eb1a76f34/