Saturday, April 30, 2016

How to break out of a nested for-loop in Java

You'd normally think that it's impossible to break out of a double, triple or n-times nest loops in Java without using some convoluted piece of code that  involves some kind of boolean checking  but it is possible, and it's pretty darn simple. It's just one of those things that you never learned about in your high school or college java class.

Anyway, here it is, with all its beauty:

outerloop: for(int i = 0; i < 20; i++) {
       for(int j = 0; j < 10; j++) {
            if(i == 10) {
               break outerloop;
            }
       }
}

Yes, it's that simple. Who knew you could label loops in Java.

No comments:

Post a Comment