Java Break/Continue
Java Break
Similar to break in switch statement, we use it in while and for statement to “jump out” of a loop.
Example
for(int i=0; i<5; i++){ if (i==3) break; System.out.println(i); }
Output
0 1 2
Java Continue
The continue statement breaks one iteration in the loop, if a specified condition is true and continues with the next iteration in the loop.
Example
for(int i=0; i<5; i++){ if (i==3) continue; System.out.println(i); }
Output
0 1 2 4
Output Explained
The above example skips the value of 4.
Break and Continue in While loop
You can also use break and continue in while loops.
Break – Example
int i = 0; while (i<5){ System.out.println(i); i++; if (i==3) break; }
Output
0 1 2
Continue – Example
while (i<5){ i++; if (i==3) continue; System.out.println(i); }
Output
1 2 4 5