Java Break
We already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch statement.
To jump out of a loop the break statement can also be used.
This example jumps out of the loop when x is equal to 9:
Example
public class BreakStatmentDemo {
public static void main(String[] args) {
for (int x = 0; x < 10; x++) {
if (x == 9) {
break;
}
System.out.println(x);
}
}
}
Output:
0
1
2
3
4
5
6
7
8
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 8
Example
public class ContinueStatmentDemo {
public static void main(String[] args) {
for (int x = 0; x < 10; x++) {
if (x == 8) {
continue;
}
System.out.println(x);
}
}
}
Output:
0
1
2
3
4
5
6
7
9
Break and Continue in While Loop
We can also use break and continue in while loops:
Break Example
public class BreakStatmentDemo {
public static void main(String[] args) {
int x = 0;
while (x < 10) {
if (x == 8) {
x++;
break;
}
System.out.println(x);
x++;
}
}
}
Continue Example
public class ContinueStatmentDemo {
public static void main(String[] args) {
int x = 0;
while (x < 10) {
if (x == 8) {
x++;
continue;
}
System.out.println(x);
x++;
}
}
}
See below video to understand more about while loop