Understanding Continue And Break Statements In Java

The break and continue keywords are the very important aspect of control structures in Java. Control Structures are the blocks of programming and consists of loops like for loop, while loop and if-else statements. Both the statements work quite similarly although they have different purposes. Let’s have a look at how they work.

Continue Statement

The purpose of continue statement is to skip the remaining control structure (any loop or if-else statement) code for some particular value of iteration.

public class Main {

    public static void main(String[] args) {
    int num=100;
        for (int i = -5; i <= 5 ; i++) {
            if (i==0)
                continue;
            System.out.println(num/i);
        }
    }
}

Now as you can see that for loop executes for i=-5,-4,…,4,5. For every value of i, it divides num which equals 100. Now if i=0 and it divides num, what would happen? As expected, the program will crash. So to prevent this, we’re using continue statement. When i reaches 0, the division isn’t performed and instead continue statement is executed which skips the execution of rest of the code of the loop and starts from next iteration i.e. i=1.

Break Statement

The purpose of break statement is terminating any loop or switch statement and get out of it. The next statement to be executed is next line outside the loop.

public class Main {

    public static void main(String[] args) {
        for (int i = 0; i <=5 ; i++) {
            if (i==4)
                break;
            System.out.println(i);
        }
    }
}

The output of this program is:

0
1
2
3

You can see that loop executes for i=0 to i=5 but when i becomes 4, we use break statement which stops further execution and 4 and 5 are not printed.

Have any query? Feel free to share with us in comments.

Related posts