Break and Continue Statement in Java

Break and continue statement in java : Like goto statement in c, there is break and continue statement to transfer control in the program. Whenever certain condition matches in the code, you may won’t to transfer your code’s flow to some other parts of the code. In such scenario, we use break and continue statement. We also use return statement to transfer control, which I’ve discussed here.

Break and Continue Statement in Java

Lets see the explanation of break and continue statement through this simple example:

public class Test {
    public static void main(String[] args) {
        int[] arr = {1,3,23,44,35,4,5};
        int searchNum = 3;
        boolean flag = false;
       
        for(int i = 0; i < arr.length(); i++) {
            if(arr[i] == searchNum) {
                flag = true;
                break;
            }
        }
        if(flag) {
            System.out.println("The search number is found");
        } else {
            System.out.println("The search number is not found");
        }
    }
}

In the above code, for-loop runs for two iteration only; because, when i = 1, the if-condition gets satisfied and the control of the code exit from the for-loop iteration. This way we can get out of the certain loop or from certain point of code when our condition get satisfied

Now lets talk about the continue statement. 

public class Test {
    public static void main(String[] args) {
        int[] arr = {1,3,23,44,35,4,5};
        int searchNum = 3;
        boolean flag = false;
       
        for(int i = 0; i < arr.length(); i++) {
            if(arr[i] != searchNum) {
                continue;
            }
            System.out.print("Search number is found");
        }
    }
}

Output: Search number is found

In the above code, the if-condition is checked and enter into it, where there is continue statement, that drives the code control to next iteration of loop, avoiding the code below the if-condition. As a result, the output is printed only one time when the if-condition is not satisfied.

So the basic difference between break and continue statement in java is that, break statement takes the control out of the loop where as continue statement takes the control to the next iteration of the loop, without implementing the code below continue statement. That’s it.