Java continue statement

The continue statement is used within loops. When the continue statement is encountered, the remaining part of the loop body is not executed and control moves to the next iteration i.e. in case of while and do while loop, control moves to the condition part on encountering teh continue statemnet whereas in for loops, control moves to increment / decreemnt part.

We will illustrate the use of continue statement through the following code snippet which prints numbers from 1 to 10.

int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 10);
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

Here are the modified versions of the above codes which will print all numbers from 1 to 10 except 7.

int i = 0;
while (i <= 9) {
    i++;
    if (i == 7) {
        continue;
    }
    System.out.println(i);
}
int i = 0;
do {
    i++;
    if (i == 7) {
        continue;
    }
    System.out.println(i);
} while (i <= 9);
for (int i = 1; i <= 10; i++) {
    if (i == 7) {
        continue;
    }
    System.out.println(i);
}

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>