Wednesday, 8 November 2017

Difference Between Break and Continue Statements in java

November 08, 2017 Posted by Prakash No comments

Difference Between Break and Continue Statements in Java

The keywords break and continue keywords is a part of control structures in Java. Sometimes break and continue seem to do the same thing but there is a difference between them.
The break keyword is used to breaks(stopping) a loop execution, which may be a for loop, while loop, do while or for each loop.
The continue keyword is used to skip the particular recursion only in a loop execution, which may be a for loop, while loop, do while or for each loop.
Example:
class BreakAndContinue
{
    public static void main(String args[])
    {
        // Illustrating break statement (execution stops when value of i becomes to 4.)
        System.out.println("Break Statement\n....................");

        for(int i=1;i<=5;i++)
        {
            if(i==4) break;
            System.out.println(i);
        }

        // Illustrating continue statement (execution skipped when value of i becomes to 1.)
        System.out.println("Continue Statement\n....................");

        for(int i=1;i<=5;i++)
        {
            if(i==1) continue;
            System.out.println(i);
        }
    }
}
Program Output:
Break Statement
....................
1
2
3

Continue Statement
....................
2
3
4
5

0 comments:

Post a Comment