Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested loops continue java

Tags:

java

I have the following for loop :

for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
    }
}

I would like to break out of the inner loop and continue the iteration of the outer loop. How do I do this?

like image 434
Troll PC Avatar asked Mar 07 '26 02:03

Troll PC


2 Answers

Generally you can use a combination of lable and break to jump to where you want like this

OUTER_LOOP: for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
     break OUTER_LOOP;

    }
}

If you want to break to some where in the outer loop you do like this, put the lable where you want to jump to(outside of the current loop) and use that lable in the break statement.

 for (int i = 0; i<arr.length;i++) {
    //line code 1
   OUTER_LOOP: // line code 2
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
     break OUTER_LOOP;

    }
}
like image 103
The Scientific Method Avatar answered Mar 10 '26 10:03

The Scientific Method


break does not stop all iterations.

So if you do the following, you will only break out of the nested loop (second for) and continue the current iteration of the first for loop:

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < someArr.length; j++) {
       break;
       // NOT executed after the break instruction
    }
    // Executed after the break instruction
}
like image 33
Ronan Boiteau Avatar answered Mar 10 '26 10:03

Ronan Boiteau