Archive for April, 2007

Breaking nested for loops

Not a question so common, but one that everyone will hit along the path of coding: breaking out of a nested for loop. A normal break will just take you out of the inner for loop.


System.out.println("before");
for (int i=0;i<3;i++) {
  for (int j=0;j<3;j++) {
    System.out.println("inside inner loop");
    break;
  }
  System.out.println("after inner loop"); // this will be printed
}
System.out.println("after everything");

To break out of the outer loop directly, label the outer loop using a… label. Then specify the label of the loop you’d like to break out of. You can name the label anything, as long as it’s unique within its scope. It also works if you have higher levels of nesting — by labelling the correct for loops you’ll be able to break out of it correctly.


System.out.println("before");
outer: for (int i=0;i<3;i++) {
  for (int j=0;j<3;j++) {
    System.out.println("inside inner loop");
    break outer;
  }
  System.out.println("after inner loop"); // this won't be printed
}
System.out.println("after everything");

Comments