Java Break and Continue
Learners can benefit from this post to better understand Java break and Continue with examples.
A break statement skips some statements, while a continue statement terminates the loop immediately without checking the test expression.
For, while, or do-while loops can be used with these statements.
To exit the loop immediately, a Java break statement can be applied.
The loop is stopped at the break statement, and control is immediately returned to the first statement following the loop.
A break statement is generally called for in cases where we aren’t sure how many iterations the loop will have. This is because we wish to terminate the loop based on some condition.
A break statement was already used in an earlier chapter of this tutorial. This statement was used to exit a switch statement.
You can also use the break statement to jump out of a loop.
A loop is terminated when mrx is equal to 6 in the following example:
If a specified condition occurs, the continue statement breaks one iteration (in the loop), and continues with the next.
The value 3 has been skipped in this example:
Similarly, the value “5” is not printed:
Break and Continue in While Loop
In while loops, you can also use break and continue:
Break vs continue:
|Break statements terminate loops immediately.||It is used to skip the current loop iteration.|
|A break statement in Java is indicated by the break keyword.||A continue statement in Java is indicated by the continue keyword.|
|The switch statement can be broken with a break.||Continue with the switch statement is not possible.|
|Breaking the loop early terminates it.||A continue statement triggers the next iteration at the beginning.|
|This will stop the loop from running.||The loop will not be stopped by using continue statement.|