How break out of both loops occurs
- There are situations we need to be 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 a two-dimensional array.
- Nesting looping e.g. printing pascal triangle and printing those star structures exercises from school days.
Depending upon some condition we also like to come 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 loops. There is a feature called labeled break, which you can use to break from nested loop. Label with break you can terminate a particular loop in nested loop structure.
How to use Label in Java
- There are two steps to break from nested loop, first part is labeling loop and second part is using labeled break.
- We must put our label before loop and need a colon after the label.
- When using that label after break, control will jump outside of the labeled loop. This means if there are 10 level of nested loop, it can break from all of them by just calling break and label of first loop. Similarly using labeled continue, it starts continuing from the labeled loop
- Label in Java is little different then goto. labeled break has no similarity with goto because it don’t allow you to go on a particular line, all you go is outside the loop.
- Labeled continue is little bit similar to goto because it goes to the loop again but not at any arbitrary point, since continue can only be used with loop, effect is limited to the loops only.
- To exit at any point inside an inner loop better use return statement. For this we need to externalize the code into a method and then call it, now at any point if want to go out of the loop, just call return without any value. This will improve readability.
How to break from nested Loop in Java
- The sample code of breaking nested loop in Java, we just have two loops, OUTER and INNER.
- We are printing number in both the loop but once the product of two counters exceed 5, we break out from the outer loop.
- This makes program complete because we also come out of main method.
- In the next example, the same logic has been developed using a method and return statement called breakFromNestedLoop()
- To break out from nested loop consider using a method and return statement over labeled break statement.
Breaking from nested loop
breaking from nested loop using return