break vs continue in Java

In this post, we will learn the difference between break and continue in Java statements in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between break and continue Statements in Java

Feature break Statement continue Statement
Usage Used to terminate the loop prematurely. Used to skip the current iteration and continue to the next one.
Loop Type Can be used with any loop (for, while, do-while). Can be used with any loop (for, while, do-while).
Effect on Loop Execution Stops the execution of the loop and exits it. Skips the remaining code in the current iteration and proceeds to the next iteration.
Loop Control Breaks out of the loop entirely. Continues with the next iteration of the loop.
Nesting of Loops Breaks only the innermost loop. Continues only the innermost loop.

Example

Let's create an example in Java to demonstrate the usage of break and continue statements. We'll use a loop to show their functionalities. Consider the following code:
public class Main {
    public static void main(String[] args) {
        // Example using break
        System.out.println("Example using break:");
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                break; // Exit the loop when i is 3
            }
            System.out.println("Loop iteration: " + i);
        }

        // Example using continue
        System.out.println("\nExample using continue:");
        for (int j = 1; j <= 5; j++) {
            if (j == 3) {
                continue; // Skip this iteration when j is 3
            }
            System.out.println("Loop iteration: " + j);
        }
    }
}

Output:

Example using break:
Loop iteration: 1
Loop iteration: 2

Example using continue:
Loop iteration: 1
Loop iteration: 2
Loop iteration: 4
Loop iteration: 5

Explanation: 

In the first example using break, the loop iterates from 1 to 5. When the loop variable i becomes 3, the if condition is true, and the break statement is executed. This causes the loop to terminate immediately, and the remaining iterations are skipped. 

In the second example using continue, the loop iterates from 1 to 5. When the loop variable j becomes 3, the if condition is true, and the continue statement is executed. This skips the current iteration and moves to the next iteration without executing the rest of the code inside the loop for that iteration. 


Comments