In Java, continue will end execution of the nearest loop's current iteration and move to the next. So:
Code:
for ( int i = 0; i < 10; i++ ) {
if ( i == 5 )
continue;
System.out.println ( "Iteration: " + i );
}
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 6
Iteration 7
Iteration 8
Iteration 9
In a nested loop, the inner-most loop is the one that break or continue has an effect on:
Code:
for ( int i = 0; i < 2; i++ ) {
for ( int j = 0; j < 2; j++ ) {
if ( i == 0 )
continue;
System.out.println ( "Iterations: " + i + " " + j );
}
}
Output:
Iterations: 1 0
Iterations: 1 1
Break, on the other hand, terminates execution of the nearest loop or switch statement. Execution does not move to the next iteration, it goes to the next statement after the loop:
Code:
for ( int i = 0; i < 10; i++ ) {
if ( i == 5 )
break;
System.out.println ( "Iteration: " + i );
}
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
The same goes for nested loops as with continue. The inner-most loop is the one acted on:
Code:
for ( int i = 0; i < 2; i++ ) {
for ( int j = 0; j < 2; j++ ) {
if ( i == 0 )
break;
System.out.println ( "Iterations: " + i + " " + j );
}
}
Output:
Iterations: 1 0
Iterations: 1 1
If you want to break from a nested loop, you can use a labeled break:
Code:
outer:
for ( int i = 0; i < 2; i++ ) {
for ( int j = 0; j < 2; j++ ) {
if ( i == 1 )
break outer;
System.out.println ( "Iterations: " + i + " " + j );
}
}
Output:
Iterations: 0 0
Iterations: 0 1