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
break is for termination: It stops the entire loop or exits a switch case.continue is for skipping: It skips the current iteration and moves to the next one.First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.