How do I break from the main/outer loop in a double/nested loop?

Using a labeled break:

mainloop:
for(){
 for(){
   if (some condition){
     break mainloop;
   }
  }
}

Also See

  • “loop:” in Java code. What is this, and why does it compile?
  • Documentation

You can just return the control from that function. Or use the ugly break labels approach :)

If there is another code parts after your for statement, you can refactor the loops in a function.

IMO, the use of breaks and continue should be discouraged in OOP, since they affect the readability and the maintenance. Sure, there are cases where they are handy, but in general I think that we should avoid them, since they will encourage the use of goto style programing.

Apparently variations to this questions are posted a lot. Here Peter provided some good and odd uses using labels.


You can add labels to your loop, and use that labelled break to break out of the appropriate loop: -

outer: for (...) {
    inner: for(...) {
        if (someCondition) {
            break outer;
        }
    }
}

See these links for more information:

  • Branching Statements
  • JLS - Break Statement

It looks like for Java a labeled break appears to be the way to go (based on the consensus of the other answers).

But for many (most?) other languages, or if you want to avoid any goto like control flow, you need to set a flag:

bool breakMainLoop = false;
for(){
    for(){
        if (some condition){
            breakMainLoop = true;
            break;
        }
    }
    if (breakMainLoop) break;
}