Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how does break interact with nested loops?

Tags:

java

break

I know a break statement jumps out of a loop, but does it jump out of nested loops or just the one its currently in?

like image 234
Craig Avatar asked Feb 23 '11 21:02

Craig


People also ask

Does Break Break Out of all loops Java?

The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop. We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.

Does break only exit one loop Java?

the break only exits loop B , so the code will loop forever. This code will not loop forever, because the break explicitly leaves loop A . Fortunately, this same logic works for continue .

How can you break out of a for loop inside a nested loop?

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.

What break will do in for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop.


1 Answers

Without any adornment, break will just break out of the innermost loop. Thus in this code:

while (true) { // A     while (true) { // B          break;     } } 

the break only exits loop B, so the code will loop forever.

However, Java has a feature called "named breaks" in which you can name your loops and then specify which one to break out of. For example:

A: while (true) {     B: while (true) {          break A;     } } 

This code will not loop forever, because the break explicitly leaves loop A.

Fortunately, this same logic works for continue. By default, continue executes the next iteration of the innermost loop containing the continue statement, but it can also be used to jump to outer loop iterations as well by specifying a label of a loop to continue executing.

In languages other than Java, for example, C and C++, this "labeled break" statement does not exist and it's not easy to break out of a multiply nested loop. It can be done using the goto statement, though this is usually frowned upon. For example, here's what a nested break might look like in C, assuming you're willing to ignore Dijkstra's advice and use goto:

while (true) {     while (true) {         goto done;     } } done:    // Rest of the code here. 

Hope this helps!

like image 83
templatetypedef Avatar answered Oct 13 '22 03:10

templatetypedef