There are situations we need nested loops in Java, one loop containing another loop e.g. to implement many
O(n^2) or quadratic algorithms e.g.
bubble sort,
insertion sort, selection sort, and
searching in two dimensional array. There are couple of more situations where you need nested looping e.g. printing pascal triangle and printing those star structures exercises from school days. Sometime depending upon some condition we also like to came out of both inner and outer loop. For example while searching a number in a two dimensional array, once you find the number, you want to come out of both loop. Question is how can you break from nested loop in Java. You all know about break right? you have seen break in switch statements, or terminating for, while and do while loop, but not many Java developer know but there is a feature called labeled break, which you can used to break from nested loop. All the places, where you have used break before is example of unlabeled break, but once you use label with break you can terminate a particular loop in nested loop structure. In order to use labeled for loop, you first need to label each loop as
OUTER or
INNER, or whatever you want to call them. Then depending upon from which loop you want to exit, you can call break statement as shown in our example. By the way, there is a better way to do the same thing, by externalizing the code of nested loop into a method and using return statement for coming out of the loop. This improves readability of your algorithm by giving appropriate name to your logic.