Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3525

Breaking Out of Nested Loops

$
0
0

1. Overview

In this tutorial, we’ll create some examples to show different ways to use break within a loop. Next, we’ll also see how to terminate a loop without using break at all.

2. The Problem

Nested loops are very useful, for instance, to search in a list of lists.

One example would be a list of students, where each student has a list of planned courses. Let’s say we want to find the name of one person that planned course 0.

First, we’d loop over the list of students. Then, inside that loop, we’d loop over the list of planned courses.

When we print the names of the students and courses we’ll get the following result:

student 0
  course 0
  course 1
student 1
  course 0
  course 1

We wanted to find the first student that planned course 0. However, if we just use loops then the application will continue searching after the course is found.

After we find a person who planned the specific course, we want to stop searching. Continuing to search would take more time and resources while we don’t need the extra information. That’s why we want to break out of the nested loop.

3. Break

The first option we have to go out of a nested loop is to simply use the break statement:

String result = "";
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
    result += "outer" + outerCounter;
    for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
        result += "inner" + innerCounter;
        if (innerCounter == 0) {
            break;
        }
    }
}
return result;

We have an outer loop and an inner loop, both loops have two iterations. If the counter of the inner loop equals 0 we execute the break command. When we run the example, it will show the following result:

outer0inner0outer1inner0

Or we could adjust the code to make it a bit more readable:

outer 0
  inner 0
outer 1
  inner 0

Is this what we want?

Almost, the inner loop is terminated by the break statement after 0 is found. However, the outer loop continues, which is not what we want. We want to stop processing completely as soon as we have the answer.

4. Labeled Break

The previous example was a step in the right direction, but we need to improve it a bit. We can do that by using a labeled break:

String result = "";
myBreakLabel:
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
    result += "outer" + outerCounter;
    for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
        result += "inner" + innerCounter;
        if (innerCounter == 0) {
            break myBreakLabel;
        }
    }
}
return result;

A labeled break will terminate the outer loop instead of just the inner loop. We achieve that by adding the myBreakLabel outside the loop and changing the break statement to stop myBreakLabel. After we run the example we get the following result:

outer0inner0

We can read it a bit better with some formatting:

outer 0
  inner 0

If we look at the result we can see that both the inner loop and the outer loop are terminated, which is what we wanted to achieve.

5. Return

As an alternative, we could also use the return statement to directly return the result when it’s found:

String result = "";
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
    result += "outer" + outerCounter;
    for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
        result += "inner" + innerCounter;
        if (innerCounter == 0) {
            return result;
        }
    }
}
return "failed";

The label is removed and the break statement is replaced by a return statement.

When we execute the code above we get the same result as for the labeled break. Note that for this strategy to work, we typically need to move the block of loops into its own method.

6. Conclusion

So, we’ve just looked at what to do when we need to exit early from a loop, like when we’ve found the item we’re searching for. The break keyword is helpful for single loops, and we can use labeled breaks for nested loops.

Alternatively, we can use a return statement. Using return makes the code better readable and less error-prone as we don’t have to think about the difference between unlabeled and labeled breaks.

Feel free to have a look at the code over on GitHub.


Viewing all articles
Browse latest Browse all 3525

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>