Home / Questions / What is the difference between a break statement and a continue statement?
Explanatory Question

What is the difference between a break statement and a continue statement?

👁 763 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

The break and continue statements are both control flow statements in Java, but they serve different purposes in loops or switch cases. Here's a detailed comparison:


Difference Between break and continue in Java

Feature break Statement continue Statement
Purpose Terminates the loop or switch case entirely. Skips the remaining part of the current iteration and moves to the next iteration.
Effect on Loop Exits the loop completely. Continues with the next iteration of the loop.
Usage in Loops Ends the loop execution when a specific condition is met. Skips certain iterations based on a condition.
Usage in Switch Case Exits the switch block. Not applicable in switch statements.
Scope Ends the nearest enclosing loop or switch case. Affects only the current iteration of the loop.

Examples

Using break Statement:


public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                break; // Exits the loop when i equals 3
            }
            System.out.println("i = " + i);
        }
        System.out.println("Loop terminated.");
    }
}

Output:


i = 1
i = 2
Loop terminated.

Using continue Statement:


public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // Skips the iteration when i equals 3
            }
            System.out.println("i = " + i);
        }
        System.out.println("Loop completed.");
    }
}

Output:


i = 1
i = 2
i = 4
i = 5
Loop completed.

Key Points to Remember

  1. break is for termination: It stops the entire loop or exits a switch case.
  2. continue is for skipping: It skips the current iteration and moves to the next one.
  3. Both affect the nearest enclosing loop: In nested loops, they only affect the loop they are directly in.