wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes continue statement... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "continue statement..." Watch "continue statement..." New topic
Author

continue statement...

Chetan Dodiya
Ranch Hand

Joined: Jun 27, 2008
Posts: 39
Can any one explain me the CONTINUE statement and how it can be used in the loops...
and what are the rules for using continue statement???


SCJP 1.5
Steven Landers
Ranch Hand

Joined: Nov 02, 2008
Posts: 30
"continue" just means "skip the rest of this iteration, and go to the next iteration of the loop I'm in"

Here's an arguably silly example:

// This will print odd numbers from 0 to 9
for(int i=0; i<10; i++){
if(i%2==0){
continue;
}
System.out.println("This is an odd number: "+i);
}
Chetan Dodiya
Ranch Hand

Joined: Jun 27, 2008
Posts: 39
but what, when i use it with label and unlabeled???
Steven Landers
Ranch Hand

Joined: Nov 02, 2008
Posts: 30
This program prints 0123456789done



You'll note that while x is less than 10, the program will print x, then continue 'with the next iteration of the loop assigned to label myLabel'

When complete, it will break the loop assigned to label 'myLabel' and print done.

The best way to learn is to try small examples like this. Copy this into your code, and manipulate it.

On your own - find out what happens if:
- myLabel: is moved above the int x = 0; assignment.
- Put another label, with another loop inside the while loop - and try continuing/breaking between labels.
- Put a return statement in certain areas throughout the code. Where would a 'return' prevent compilation due to unreachable code?
- Other new information you may find? Share with us!

These are the types of things tested by SCJP.
Chetan Dodiya
Ranch Hand

Joined: Jun 27, 2008
Posts: 39
Thank you very much...
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
This is how 'continue' works; consider this code fragment:

for( int i=0; i < 4;i++ )
{
System.out.println("before="+i);
if ( i==2)
continue;
System.out.println("after="+i);
// c
}

When i takes the value 2, the 'if...continue' passes control to just before '}' and the second print statement does not execute.

The output of the program is:
before 0
after 0
before 1
after 1
before 2
before 3
after 3

Hope that helps.
 
Consider Paul's rocket mass heater.
 
subject: continue statement...