Java: Break and Continue Statements

Since most control flow statements in Java have been covered, it is a good time to look at branching statements.

A branching statement aims to instruct the compiler to branch to some other line in the code. Usually, branching statements are used in loops as well as other control flow statements.

Break Statement

First, the break statement will be discussed. Its use in the switch statement has already been witnessed and used. Apart from the switch statement, a break statement can be used in several other control flow statements. That is because it enables the premature exiting of a loop once the predetermined condition is returned true. Now, the use of a break statement in a for statement is explored.

Consider the code segment below:

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

Here, the if statement has been used inside a for statement. In Java programs, different control statements are often combined and used together to get the desired results. Other examples include while statements inside if statements and for statements inside while statements, which are referred to as nested control statements.

Running the code above will provide the following output:  

i = 0
i = 1
i = 2
i = 3
i = 4

Although the for condition requires the loop to go on till i reaches 5, the loop ends at 4 itself.  

If the break statement was not used, the loop would have continued till i became 5, because according to our condition, the loop must go on till i < 6. However, the break statement ensures that the loop is ended when i became 4 as the fourth line is assessed to be true, which leads to the execution of the break statement.   

Continue Statement

The continue statement is another very commonly used branching statement. Using continue skips any statements that follow the statement for that particular iteration. Let us look at a simple example.

Running the code mentioned below

public class ForJava { 
    public static void main(String[] args) {
        for (int i = 0; i < 7; i++) {
            System.out.println("i = " + i); 
            if (i == 5)
                continue;
            System.out.println("Not visible when i=5."); 
        }
    }
}

Output:

i = 0
Not visible when i=5.
i = 1
Not visible when i=5.
i = 2
Not visible when i=5.
i = 3
Not visible when i=5.
i = 4
Not visible when i=5.
i = 5
i = 6
Not visible when i=5.

When i = 5, the line following the continue statement is neither executed nor printed. After skipping that statement, the program runs again from the first line, and the execution begins again. 

Leave a Reply

%d bloggers like this: