W3docs

Java break Statement

Exit loops and switch blocks early in Java with the break statement, including labeled break.

break is the emergency exit. It immediately stops the innermost loop or switch block it's inside, and execution continues with whatever follows. Use it when the work of the loop is done and there's no reason to keep iterating.

Breaking out of a loop

for (int i = 0; i < 100; i++) {
  if (i == 5) {
    break;
  }
  System.out.println(i);
}
// continues here

Prints 0 1 2 3 4 and exits. The loop's condition (i < 100) and update (i++) are abandoned the moment break runs.

A typical use: search for an item, stop as soon as you find it:

int[] nums = {3, 7, 2, 8, 5};
int target = 8;
int foundAt = -1;

for (int i = 0; i < nums.length; i++) {
  if (nums[i] == target) {
    foundAt = i;
    break;
  }
}
System.out.println("found at index: " + foundAt);

Without break, you'd keep checking elements you already know aren't the answer.

break in a while

Works identically in while and do/while:

int n = 1;
while (true) {
  if (n > 1000) {
    break;
  }
  n *= 2;
}
System.out.println(n);   // 1024

while (true) { ... break; } is the standard pattern for "loop until some condition decided inside the body."

break in a switch

In a traditional switch statement, break exits the switch — preventing fall-through to the next case. You saw this in the switch chapter:

switch (cmd) {
  case "start": startServer(); break;
  case "stop":  stopServer();  break;
  default:      help();        break;
}

The arrow-form switch expressions covered in switch expressions don't fall through, so they don't need break.

break only exits one level

break exits the innermost enclosing loop or switch. In nested loops, it leaves only the inner one:

for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 3; j++) {
    if (j == 1) break;     // only exits the inner loop
    System.out.println(i + "," + j);
  }
}

Output:

0,0
1,0
2,0

To exit all nested loops at once, use a labeled break — covered in labeled statements:

outer:
for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 3; j++) {
    if (i == 1 && j == 1) break outer;
    System.out.println(i + "," + j);
  }
}

break vs return

If the work that comes after the loop is significant, use break. If the method has nothing more to do once the loop ends, just return directly:

for (int i = 0; i < nums.length; i++) {
  if (nums[i] == target) {
    return i;       // shorter than break + return after the loop
  }
}
return -1;

Both are correct. return is often the cleaner choice for search-style methods.

A worked example

java— editable, runs on the server

What's next

break exits the loop entirely. To skip just the current iteration and continue with the next one, use continue.

Practice

Practice

Inside a nested for loop, a plain break statement...