Java break statement

In Java, break exits the nearest enclosing loop or switch statement. A labeled break can exit a named enclosing statement.

A simple example

Stop before printing 3

  1. Start with Visit 1 through 4
  2. Do this Leave at 3
  3. Result 1 → 2
When the number reaches 3 the loop ends. The print step is skipped for 3 and 4.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        for (int n = 1; n <= 4; n++) {
            if (n == 3) {
                break;
            }
            System.out.println(n);
        }
    }
}
Output
1
2
Credit balance: 10 → 6 → 3. Next job costs: 8 credits. Queue result: 2 jobs accepted.
Stop at the first job that will not fit

A print queue has ten credits and must serve jobs in arrival order. Jobs costing four and three leave three credits. The next job costs eight, so the queue stops before the smaller job behind it.

  • Break Statement
  • Labeled Break Statement