How to break from nested loop in Java

There are situations we need to be nested loops in Java, one loop containing another loop e.g. 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 e.g.  printing 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 loop. 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 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 developer know but there is a feature called labeled break, which you can use to break from nested loop.

All the places, where you have used break before is example of unlabeled break, but once you use label with break you can terminate a particular loop in 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 from 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 return statement for coming out of the loop. This improves readability of your algorithm by giving appropriate name to your logic. See Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statement in Java.




How to use Label in Java

There are two steps to break from nested loop, first part is labeling loop and second part is using labeled break. You must put your label before loop and you need a colon after the label as well. When you use that label after 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 programmer, 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 use label with break in Java


How to break from nested Loop in Java

How to break from nested loop in JavaHere is the sample code of breaking nested loop in Java. In this example, we just have two loops, OUTER and INNER. We are printing number in both the loop but once the product of two counters exceed 5, we break out from the outer loop. This makes program complete because we also come out of 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 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 nested loop in Java. You have seen that how you can use label with break statement to terminate the outer loop from inner loop, but you can do much better with encapsulating the loop in a method and then using return statement to break from nested loop. You can also use label with continue statement as well.


2 comments:

  1. How to you print following structure in Java

    **********
    *********
    ********
    *******
    ******
    *****
    ****
    ***
    **
    *

    ReplyDelete
  2. Modified Snippet code :
    for (int i = rows; i > 0; i--) {
    for (int j = i; j >= 1; j--) {
    System.out.print("*");
    }

    System.out.println();
    }

    ReplyDelete