The continue statement can be used with
loop control statement such as for loop, while loop and do-white loop. If we
want to skip some statements in a loop, continue statement can be used. The
continue statement can be written anywhere inside a loop body. When continue
statement is encountered inside a loop, control jumps to the end of the loop
and test expression is evaluated. In case of for loop, update statement is
executed and then test expression is evaluated.
Syntax of continue statement
continue;
Example of java continue statement
class ContinueStatement
{
public static void main(String[] args) {
int i;
for (i =1; i<=10 ; i++) {
if(i==5 || i==6){
continue;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
7
8
9
10
When i = 5 or i = 6, continue statement is executed and
control jump to the update statement of for loop. This is the
reason why 5 and 6 is printed.
Continue Statement with Inner Loop
If continue statement is encountered in
inner loop, then it continues only inner loop. And test expression is evaluated
of inner loop. In case of for loop, update statement of inner loop is evaluated
and then test expression is evaluated.
Example:
class ContinueStatement
{
public static void main(String[] args) {
int i, j;
for (i = 1; i<=5 ; i++) {
for (j = 1; j<=5; j++) {
if(i>3 && j>3){
continue;
}
System.out.println("i = "+i+" "+"j = "+j);
}
}
}
}
Output:
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 1 j = 5
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4
i = 2 j = 5
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3
i = 3 j = 4
i = 3 j = 5
i = 4 j = 1
i = 4 j = 2
i = 4 j = 3
i = 5 j = 1
i = 5 j = 2
i = 5 j = 3
When (i>3 && j>3) condition holds true, then value of i and j is not displayed. Otherwise, value of i and j is displayed.
0 comments:
Post a Comment