Q: Breaking out of nested loops in Java

D: Now how can I break out of both loops. I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos. I don't want to put the inner loop in a different method. Update: I don't want to rerun the loops, when breaking I'm finished with the execution of the loop block

Test Case #12


File ID: #886979-1-cc


public class BreakOuter {
    public static void main(String[] args) {
        outerloop:
        for (int i =0; i < 5; i + +) {
            for (int j =0; j < 5; j + +) {
                if (i * j > 6) {
                    System.out.println("Breaking");
                    break outerloop;
                }
                System.out.println(i + " " + j);
            }
        }
        System.out.println("Done");
    }
}

  1. I'll never do that again, I promise ;)
  2. It looks like a goto method I did not like this one.
  3. - that claim is clearly true - in languages that promise that it's true. But Java doesn't make that promise. If a language is in conflict with your assumptions, it's possible that it's your assumptions that are at fault. In this case, I think you are still partly right - principle of least surprise WRT the many who never heard of (or forgot about) that form of `break`. Even then, exceptions are another better-known exception (sorry). But I'd still be unhappy about this if it was not obvious (small loops, warning comment if the label/break still are not visible enough).

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: