There are situations we need to be nested loops in Java, one loop containing another loop like to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array. There are a couple of more situations where you need nesting looping like printing the pascal triangle and printing those star structures exercises from school days. Sometimes depending upon some condition we also like to come out of both inner and outer loops. For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. The question is how can you break from the nested loop in Java.
You all know about break right? you have seen a break in switch statements, or terminating for, while and do-while loop, but not many Java developers know but there is a feature called a labeled break, which you can use to break from the nested loop.
All the places, where you have used break before is an example of unlabeled break, but once you use a label with the break you can terminate a particular loop in a nested loop structure.
All the places, where you have used break before is an example of unlabeled break, but once you use a label with the break you can terminate a particular loop in a 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 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 a return statement for coming out of the loop. This improves the readability of your algorithm by giving an appropriate name to your logic. See Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statements in Java.
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 a return statement for coming out of the loop. This improves the readability of your algorithm by giving an appropriate name to your logic. See Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statements in Java.
How to Break from a Nested Loop in Java using Label
There are two steps to break from a nested loop, the first part is labeling loop and the second part is using labeled break. You must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop.This means if you have 10 level of nested loop, you can break from all of them by just calling break and label of first loop. Similarly if you use labeled continue, it starts continuing from the labeled loop.
This gives Java developer immense power, similar to what goto gives to C programmers, but label in Java is little different then goto.
This gives Java developer immense power, similar to what goto gives to C programmers, but 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.
By the way, In practice, if you want to exit at any point inside an inner loop then you should better use return statement. For this you need to externalize the code into a method and then call it, now at any point you want to go out of the loop, just call return without any value. This will improve readability.
As I said before, you can also see Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statement in Java.
By the way, In practice, if you want to exit at any point inside an inner loop then you should better use return statement. For this you need to externalize the code into a method and then call it, now at any point you want to go out of the loop, just call return without any value. This will improve readability.
As I said before, you can also see Core Java Volume 1 - Fundamentals to learn more about how to use a label with break and continue statement in Java.
How to break from nested Loop in Java
Here is the sample code for breaking the nested loop in Java. In this example, we just have two loops, OUTER and INNER. We are a printing number in both the loop but once the product of two counters exceeds 5, we break out from the outer loop.This makes the program complete because we also come out of the main method. In the next example, the same logic has been developed using a method and return statement called breakFromNestedLoop(), you can see that how much it improve the readability.
So next time if you have to break out from the nested loop consider using a method and return statement over labeled break statement.
That's all about how to break from a nested loop in Java. You have seen that how you can use the label with a break statement to terminate the outer loop from the inner loop, but you can do much better with encapsulating the loop in a method and then using a return statement to break from a nested loop. You can also use a label with a continue statement as well.
import java.io.IOException; /** * How to break from nested loop in Java. You can use labeled * statement with break statement to break from nested loop. * * @author WINDOWS 8 */ public class BreakingFromNestedLoop{ public static void main(String args[]) throws IOException { // this is our outer loop outer: for (int i = 0; i < 4; i++) { // this is the inner loop for (int j = 0; j < 4; j++) { // condition to break from nested loop if (i * j > 5) { System.out.println("Breaking from nested loop"); break outer; } System.out.println(i + " " + j); } } System.out.println("exited"); // better way is to encapsulate nested loop in a method // and use return to break from outer loop breakFromNestedLoop(); } /** * You can use return statement to return at any point from a method. * This will help you to break from nested loop as well */ public static void breakFromNestedLoop(){ for(int i=0; i<6; i++){ for(int j=0; j<3; j++){ int product = i*j; if(product > 4){ System.out.println("breaking from nested loop using return"); return; } } } System.out.println("Done"); } } Output 0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 Breaking from nested loop exited breaking from nested loop using return
Things to remember while using nested loop and break in Java
When working with nested loops and the break statement in Java, it's crucial to manage control flow effectively. Consider the scoping of variables, be cautious with labeling loops for clarity and targeted breaks, and avoid unintended infinite loops by ensuring termination conditions. These mistakes are hard to track and cost you a lot of time later.
While nested loops offer flexibility, they can reduce code readability and efficiency, so strive for a balance between simplicity and functionality. Use break judiciously, and if nesting becomes too complex, consider refactoring for improved code organization.
Always be mindful of the potential interactions between outer and inner loops to ensure the program behaves as intended, and use labeling to specify which loop the break statement should affect in the case of multiple nested loops.
That's all about how to break from a nested loop in Java. You have seen that how you can use the label with a break statement to terminate the outer loop from the inner loop, but you can do much better with encapsulating the loop in a method and then using a return statement to break from a nested loop. You can also use a label with a continue statement as well.
How to you print following structure in Java
ReplyDelete**********
*********
********
*******
******
*****
****
***
**
*
Modified Snippet code :
ReplyDeletefor (int i = rows; i > 0; i--) {
for (int j = i; j >= 1; j--) {
System.out.print("*");
}
System.out.println();
}