PDA

View Full Version : The "continue" statement in JAVA



Hexxx
02-26-2004, 03:53 PM
right now I have a code of



while (!eof) {
for (int i=0; condtion; i++) {
if (conditionX==-1) break;
blah blah;
}

if (conditionX==-1) continue;
more blah blah}


what I want to know is about the use of the "continue", does it just fallout for while loops? or can it fall out for "for loops" too.
I mean can I change


if (conditionX==-1) break;


to



if (conditionX==-1) continue


and still have it working like the original code (falling out the *complete* while and not just the for loop.)

Prelude
02-26-2004, 06:19 PM
In Java, continue will end execution of the nearest loop's current iteration and move to the next. So:


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:


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:


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:


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:


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