Difference between break and continue keywords

Break and Continue Demonstration
When we enter into loops concept we might undergo the two keywords break and continue. These two keywords 'sometimes' seem to do the same thing but they are not always the same. There is a difference between them.

The break keyword breaks a loop which may be a for loop, while loop or do while or for each. Breaking a loop means stopping it's recursion forever so that the loop executes no more. The control then goes out of the loop and executes the other statements after the loop.

The continue keyword skips the loop for a particular recursion. This keyword does not make the loop not to execute forever instead it just makes the loop to skip that particular recursion only. Not all recursions.

An example might give you a better understand.

class BreakAndContinue
{
    public static void main(String args[])
    {
        // Illustrating break

        System.out.println("Break\n----------------");

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


        // Illustrating continue

        System.out.println("Continue\n-------------");

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

    }
}

Output of the program


 Break
----------------
1
2
3
Continue
-------------
1
2
3
5

Explaining the program better 

As you can see from the output, when i used the keyword break you can see the output only 1,2,3. As you can see you didn't see 4 and 5. What happened here is that the loop broke. i.e. the loop here executes no more thereby skipping the printing of 4 and 5.

Next, when i used the continue keyword, you can see 1,2,3 and 5 but not 4. I have got a condition for the loop that if the value of i equals 4, then continue which means that the printing of 4 is skipped which implies that the next statement(s) after the continue keyword don't execute however the next iteration(s) take place. As a result you've got 5 printed there. Printing 4 is skipped that's it. But when you use break the loop itself broke.
In this way, the keywords break and continue differ. Also see transient keyword in Java


Posted by at on

Tags: Keywords,