Java Break and Continue: Controlling Loop Execution

Learn how to use the break and continue statements in Java to control the flow of loops. Discover how the break statement allows you to exit a loop early, as demonstrated in examples like stopping the loop when i equals 4. Enhance your programming skills by mastering these essential loop control mechanisms.



Java Break and Continue

Java Break

The break statement can be used to exit a loop early. The example below stops the loop when i is equal to 4:

Example

for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Output

0
1
2
3

Java Continue

The continue statement skips the current iteration and continues with the next one. The example below skips the value 4:

Example

for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Output

0
1
2
3
5
6
7
8
9

Break and Continue in While Loop

You can also use break and continue in while loops:

Break Example

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

0
1
2
3
Continue Example

int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
Output

0
1
2
3
5
6
7
8
9