Breaking Out of Inner Loop and Continuing Outer Loop

Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to break from a nested loop in Java? [Example]

There are situations we need to be nested loops in Java, one loop containing another loop like to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array. There are a couple of more situations where you need nesting looping like printing the pascal triangle and printing those star structures exercises from school days. Sometimes depending upon some condition we also like to come out of both inner and outer loops. For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. The question is how can you break from the nested loop in Java.

You all know about break right? you have seen a break in switch statements, or terminating for, while and do-while loop, but not many Java developers know but there is a feature called a labeled break, which you can use to break from the nested loop.

All the places, where you have used break before is an example of unlabeled break, but once you use a label with the break you can terminate a particular loop in a nested loop structure. In order to use labeled for loop, you first need to label each loop as OUTER or INNER, or whatever you want to call them. Then depending upon which loop you want to exit, you can call break statement as shown in our example.

By the way, there is a better way to do the same thing, by externalizing the code of nested loop into a method and using a return statement for coming out of the loop. This improves the readability of your algorithm by giving an appropriate name to your logic. See Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statements in Java.

How to Break from a Nested Loop in Java using Lable

There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.

This means if you have 10 level of nested loop, you can break from all of them by just calling break and label of first loop. Similarly if you use labeled continue, it starts continuing from the labeled loop.

This gives Java developer immense power, similar to what goto gives to C programmers, but label in Java is little different then goto. labeled break has no similarity with goto because it don't allow you to go on a particular line, all you go is outside the loop. labeled continue is little bit similar to goto because it goes to the loop again but not at any arbitrary point, since continue can only be used with loop, effect is limited to the loops only.

By the way,  In practice, if you want to exit at any point inside an inner loop then you should better use return statement. For this you need to externalize the code into a method and then call it, now at any point you want to go out of the loop, just call return without any value. This will improve readability.

As I said before, you can also see Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statement in Java.

How to break from nested loop in Java

How to break from nested Loop in Java

Here is the sample code for breaking the nested loop in Java. In this example, we just have two loops, OUTER and INNER. We are a printing number in both the loop but once the product of two counters exceeds 5, we break out from the outer loop.

This makes the program complete because we also come out of the main method. In the next example, the same logic has been developed using a method and return statement called breakFromNestedLoop(), you can see that how much it improve the readability.

So next time if you have to break out from the nested loop consider using a method and return statement over labeled break statement.

                import                java.io.IOException;                /**                                  * How to break from nested loop in Java. You can use labeled                                  * statement with break statement to break from nested loop.                                  *                                                  * @author WINDOWS 8                                  */                public                class                BreakingFromNestedLoop{                public                static                void                main(String args[])                throws                IOException {                // this is our outer loop                outer:                for                (int                i =                0; i <                4; i++) {                // this is the inner loop                for                (int                j =                0; j <                4; j++) {                // condition to break from nested loop                if                (i * j >                5) {                     System.out.println("Breaking from nested loop");                break                outer;                 }                  System.out.println(i +                " "                + j);             }          }         System.out.println("exited");                // better way is to encapsulate nested loop in a method                // and use return to break from outer loop                breakFromNestedLoop();              }                /**                                  * You can use return statement to return at any point from a method.                                  * This will help you to break from nested loop as well                                  */                public                static                void                breakFromNestedLoop(){                for(int                i=0; i<6; i++){                for(int                j=0; j<3; j++){                int                product = i*j;                if(product >                4){                     System.out.println("breaking from nested loop using return");                return;                 }                             }         }         System.out.println("Done");     }  }  Output                0                0                0                1                0                2                0                3                1                0                1                1                1                2                1                3                2                0                2                1                2                2                Breaking from nested loop exited breaking from nested loop using                return              

That's all about how to break from a nested loop in Java. You have seen that how you can use the label with a break statement to terminate the outer loop from the inner loop, but you can do much better with encapsulating the loop in a method and then using a return statement to break from a nested loop. You can also use a label with a continue statement as well.

jenkinsbehen1945.blogspot.com

Source: https://www.java67.com/2014/12/how-to-break-from-nested-loop-in-java.html

0 Response to "Breaking Out of Inner Loop and Continuing Outer Loop"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel