Let\'s say I have this:
while(a){
while(b){
if(b == 10)
break;
}
}
Question: Will the break statement take m
Only from the inner one. Use labeled break if you wish to break to specific loop
label1:
for(){
label2:
for(){
if(condition1)
break label1;//break outerloop
if(condition2)
break label2;//break innerloop
}
}
Also See
Only the inner loop of course.
while (a) {
while (b) {
if (b == 10) {
break;
}
}
}
In the above code you will break the inner most loop where (ie. immediate loop
) where break
is used.
You can break both the loops at once using the break
with label
label1:
while (a) {
while (b) {
if (b == 10) {
break label1;
}
}
}
The java break statement won't take you out of multiple nested loops.
As a curious note, in PHP the break statement accept a numeric parameter which tells how many outer loops you want to break, like this:
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
It will break only the most immediate while loop. Using a label you can break out of both loops: take a look at this example taken from here
public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}