1
0

Continue Statement in Java

The continue statement skips the current iteration of a for, while, or do-while loop and starts a new iteration. The unlabeled form skips to the end of the loop’s body containing the continue statement and evaluates the boolean expression that controls the loop. The following program, ContinueDemo, steps through a String, counting the occurrences of the letter “p”. If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a “p”; the program increments the letter count.

Program to demonstrate the continue statement.

class ContinueDemo
{
    public static void main(String[] args)
    {
        String searchMe = " peter piper picked a peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;
        for (int i=0; i<max; i++)
        {
            if(searchMe.charAt(i) != 'p') // ineterested only in p's
                continue;
                numPs++;  // process p's
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

Here is the output of this program:

Found 9 p's in the string.

To see the effect more clearly, try removing the continued statement and recompiling. When you run the program again, the count will be wrong, saying that it found 35 p’s instead of 9.

Leave a Reply