How to break outer loop from inner loop in Java?

Visual representation of outer loop breaking from inner loop
Have you ever got a situation to break outer loop when in a inner loop? I got this many times. But what could I do, the simple break statement would just break the inner loop and the outer loop continues. Now, to break it, I need to be quite smarter here, I'll have to be familiar with the unfamiliar labeled blocks. One thing you can do is create a label above outer loop and use it with break. These words might be a bit confusing, however you can easily understand the program below, I am sure.


class BreakOuterLoop
{
    public static void main(String args[])
    {
   
    // Give a label
    outerLoop:{
        for(int i=0;i<10;i++)
        {
            for(int j=0;j<2;j++)
            {
                // Break to the label
                if(j==1 && i==5) break outerLoop;
                System.out.println(i+"  "+j);
            }
        }
    } // The control comes here when condition is satisfied
    // Because this is the end of outerLoop block
   
    System.out.println("End");
   
    }  
}

Output


0  0
0  1
1  0
1  1
2  0
2  1
3  0
3  1
4  0
4  1
5  0
End

I would love to hear some alternative approaches for this in the comments. Do you have any?


Posted by at on

Tags: Loops, Tricks Bag,