Java Break and Continue Statements – Complete Guide with Examples


Learn how to control the flow of loops in Java using break and continue statements with detailed examples for both simple and nested loops.

Break and Continue Statements in Java – Complete Detailed Tutorial

In Java, loop control statements like break and continue allow us to alter the normal flow of loops based on conditions.

These statements are essential for efficient loop control.

1. break Statement

  1. Terminates the current loop immediately
  2. Execution jumps outside the loop
  3. Can be used with for, while, do-while, and switch

Syntax:


break;

Example – break in for loop


for(int i = 1; i <= 10; i++) {
if(i == 5) {
break; // exit loop when i is 5
}
System.out.println(i);
}

Output:


1
2
3
4

Explanation:

  1. When i == 5, the loop terminates immediately

Example – break in while loop


int i = 1;
while(i <= 10) {
if(i == 4) break;
System.out.println(i);
i++;
}

Output:


1
2
3

2. continue Statement

  1. Skips the current iteration and moves to the next iteration
  2. Loop continues after skipping

Syntax:


continue;

Example – continue in for loop


for(int i = 1; i <= 5; i++) {
if(i == 3) continue; // skip when i is 3
System.out.println(i);
}

Output:


1
2
4
5

Explanation:

  1. The number 3 is skipped but the loop continues

Example – continue in while loop


int i = 1;
while(i <= 5) {
i++;
if(i == 4) continue;
System.out.println(i);
}

Output:


2
3
5
6

3. Using break and continue in Nested Loops

  1. break terminates inner-most loop
  2. continue skips current iteration of inner-most loop

Example – nested for loop


for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
if(j == 2) continue; // skip j=2
System.out.println("i=" + i + ", j=" + j);
}
}

Output:


i=1, j=1
i=1, j=3
i=2, j=1
i=2, j=3
i=3, j=1
i=3, j=3

Example – break in nested loop


for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
if(j == 2) break; // exit inner loop when j=2
System.out.println("i=" + i + ", j=" + j);
}
}

Output:


i=1, j=1
i=2, j=1
i=3, j=1

4. Summary

  1. breakexit loop immediately
  2. continueskip current iteration and continue
  3. Can be used in for, while, do-while, and switch
  4. In nested loops, break/continue affects inner-most loop only