0
0
JavaHow-ToBeginner · 3 min read

How to Use Break in Java: Syntax and Examples

In Java, the break statement is used to immediately exit a loop or a switch block. When break is executed, the program stops the current loop or switch and continues with the code after it.
📐

Syntax

The break statement is written simply as break;. It can be used inside loops (for, while, do-while) or inside a switch statement.

When the program reaches break;, it immediately stops the current loop or switch case and moves to the next statement after it.

java
break;
💻

Example

This example shows how break stops a for loop when a condition is met. It prints numbers from 1 to 5, then stops the loop when it reaches 6.

java
public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 6) {
                break; // Exit loop when i is 6
            }
            System.out.println(i);
        }
        System.out.println("Loop ended.");
    }
}
Output
1 2 3 4 5 Loop ended.
⚠️

Common Pitfalls

One common mistake is using break outside loops or switch statements, which causes a compile error. Another is expecting break to exit multiple nested loops; it only exits the innermost loop.

To exit outer loops, you can use labeled break statements.

java
public class BreakPitfall {
    public static void main(String[] args) {
        // Wrong: break outside loop causes error
        // break; // Uncommenting this line causes compile error

        // Nested loops example
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    break outerLoop; // Exits both loops
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}
Output
i=1, j=1
📊

Quick Reference

  • Use: To exit loops or switch cases early.
  • Syntax: break;
  • Works in: for, while, do-while, and switch.
  • Exits: Only the innermost loop unless labeled.
  • Cannot use: Outside loops or switch (compile error).

Key Takeaways

Use break; to immediately exit the current loop or switch case.
break only exits the innermost loop unless you use a label.
Do not use break outside loops or switch statements; it causes errors.
Labeled break helps exit outer loops in nested structures.
After break, the program continues with the code following the loop or switch.