Let's say I have this:
while (a) { while (b) { if (b == 10) { break; } } }
Question: Will the break statement take me out of both loops or only from the inner one? Thank you.
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.
A break statement will take you out of the innermost loop enclosing that break statement. In the example the inner while loop. Show activity on this post. The java break statement won't take you out of multiple nested loops.
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.
In your example break statement will take you out of while(b) loop
while(a) { while(b) { if(b == 10) { break; } } // break will take you here. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With