Java•Loop Control
Java Break and Continue Loop Control Statements
break terminates the enclosing loop; continue jumps directly to the next iteration.
Syntax
if (condition) break;
if (condition) continue;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| break | Keyword | Exits loop completely. |
| continue | Keyword | Skips current iteration. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Java locally:
public class Main {
public static void main(String[] args) {
int[] portCodes = {80, 443, -1, 8080, 9999, 3000};
System.out.println("Scanning ports:");
for (int port : portCodes) {
if (port < 0) {
System.out.println(" [SKIP] Invalid negative port: " + port);
continue;
}
if (port == 9999) {
System.out.println(" [STOP] Sentinel port 9999 hit. Halting scan.");
break;
}
System.out.println(" [OPEN] Active port: " + port);
}
}
}Expected Output:
Scanning ports: [OPEN] Active port: 80 [OPEN] Active port: 443 [SKIP] Invalid negative port: -1 [OPEN] Active port: 8080 [STOP] Sentinel port 9999 hit. Halting scan.
How It Works: Step-by-Step
- Lines 7-10: continue skips -1 without processing.
- Lines 11-14: break halts scan immediately upon 9999.
Key Concepts
- continue jumps to the loop update expression.
- break terminates the innermost enclosing loop.
- Java supports labeled breaks (break labelName;) to escape nested loops.
Common Mistake: Using continue in while loops before incrementing counter
Skipping the increment step in a while loop leads to an infinite loop.
❌ Incorrect
while (i < 5) {
if (i == 2) continue; // i never changes!
i++;
}✅ Correct
while (i < 5) {
if (i == 2) { i++; continue; }
i++;
}Related Java Tutorials & Compiler
Java For Loops and Enhanced For-Each Loop with Examples
Master traditional counting for loops and enhanced for-each iteration over arrays and collections.
Java While and Do-While Loops with Examples
Learn while loops for conditional iteration and do-while loops for guaranteed first execution.
Java If...Else and Ternary Conditional Statements
Implement decision-making logic using if, else if, else, and ternary operators.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.