break, continue and return

Site Admin · 11 Sep 2026 · 10 views

break

break immediately exits the loop, skipping any remaining iterations.

for (int i = 1; i <= 10; i++) {
    if (i == 5) break;   // loop stops when i reaches 5
    System.out.print(i + " ");
}
// prints: 1 2 3 4

continue

continue skips the rest of the current iteration and jumps to the next one.

for (int i = 1; i <= 6; i++) {
    if (i % 2 == 0) continue; // skip even numbers
    System.out.print(i + " ");
}
// prints: 1 3 5

return

Inside a method, return ends the method immediately. With a value it hands that value back to the caller.

static int largest(int a, int b) {
    if (a > b) return a;
    return b;
}

Labelled break and continue

Nested loops can be exited from the outer loop using a label:

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

Key Points

  • break leaves a loop; continue moves to the next iteration.
  • return ends the current method.
  • Labels target outer loops; use them sparingly for readability.
Share this post:

Comments (0)

Please login or register to comment.