Java Loops: continue Control Statement

Java Loops: continue Control Statement
0

#1

Java continue Control Statement

The continue statement makes a loop skip all the following lines after the continue and jump ahead to the beginning of the next iteration. In a for loop, control jumps to the update statement, and in a while or do while loop, control jumps to the boolean expression/condition.

for (int j = 0; j < 10; j++)
{
    if (j == 5)
    {
        continue;
    }
    System.out.print (j + " ");
}

The value of j will be printed for each iteration, except when it is equal to 5. The print statement will get skipped because of the continue and the output will be:

0 1 2 3 4 6 7 8 9

Say you want to count the number of is in a the word mississippi. Here you could use a loop with the continue statement, as follows:

String searchWord = "mississippi";

// max stores the length of the string
int max = searchWord.length();
int numPs = 0;

for (int i = 0; i < max; i++)
{
    // We only want to count i's - skip other letters
    if (searchWord.charAt(i) != 'i')
        continue;

    // Increase count_i for each i encountered
    numPs++;
}

System.out.println("numPs = " + numPs);

:rocket: Run Code


#2

Continue statement

Continue statement works like break but instead of forcing termination, it forces the next iteration of the loop to take place and skipping the rest of the code. Continue statement is mostly used inside loops, whenever it is encountered inside a loop, either conditionally or unconditionally, transfers control to the next iteration of either the current loop or an enclosing labelled loop. Examples…Java Continue Statement

Lee


#3