What is the difference between a break statement and a continue statement?
Views 648
Answer:
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 aswitch
case.continue
is for skipping: It skips the current iteration and moves to the next one.- Both affect the nearest enclosing loop: In nested loops, they only affect the loop they are directly in.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.