In Java, how does break interact with nested loops? -
i know break
statement jumps out of loop, jump out of nested loops or 1 in?
thanks.
without adornment, break
break out of innermost loop. in code:
while (true) { // while (true) { // b break; } }
the break
exits loop b
, code loop forever.
however, java has feature called "named breaks" in can name loops , specify 1 break out of. example:
a: while (true) { b: while (true) { break a; } }
this code not loop forever, because break
explicitly leaves loop a
.
fortunately, same logic works continue
. default, continue
executes next iteration of innermost loop containing continue
statement, can used jump outer loop iterations specifying label of loop continue executing.
in languages other java, example, c , c++, "labeled break" statement not exist , it's not easy break out of multiply nested loop. can done using goto
statement, though frowned upon. example, here's nested break might in c, assuming you're willing ignore dijkstra's advice , use goto
:
while (true) { while (true) { goto done; } } done: // rest of code here.
hope helps!
Comments
Post a Comment