Java:Java Break and Continue Loop Control Statements
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:

ParameterTypeDescription
breakKeywordExits loop completely.
continueKeywordSkips current iteration.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler