• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

continue statement...

 
Chetan Dodiya
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Steven Landers
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but what, when i use it with label and unlabeled???
 
Steven Landers
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much...
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic