Continue and Break Statement in Java
The continue
and break
statements in Java have the effect of interrupting the way loops are run. They can be used to bypass certain code in a loop.
Break Statement
The break
statement is used to exit out of a loop. For instance, if we've encountered a certain condition and don't want the loop to run anymore, we can force the loop to exit and not execute the next loop iterations.
Let's say we want to find the first three even numbers in an array. We could write the program using the break
keyword:
int[] numbers = new int[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };ArrayList evenNumbers = new ArrayList<>();for (int i = 0; i < numbers.length; i++) {if (numbers[i] % 2 == 0) {evenNumbers.add(numbers[i]);}if (evenNumbers.size() == 3) {// We have three even numbers now, so stop executing the loopbreak;}}
Once we find the first three numbers, the break
statement causes the loop to end, so any following loop iterations are ignored and the program continues after past the loop body.
Continue Statement
The continue
statement is used to skip the current iteration of a loop. We might have a scenario where we don't want code to execute on a given condition. When the continue
statement is encountered, then any following code within the loop body is not executed for the current iteration. The program immediately skips to the next iteration of the loop.
Say we want to write a program that gets all even numbers except for 0 and 2:
int[] numbers = new int[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };ArrayList<Integer> evenNumbers = new ArrayList<>();for (int i = 0; i < numbers.length; i++) {if (numbers[i] == 0 || numbers[i] == 2) {// Don't add numbers 0 or 2 to the listcontinue;}if (numbers[i] % 2 == 0) {evenNumbers.add(numbers[i]);}}
Conclusion
Using the break
and continue
statements are useful when we want to alter the way a loop is run. Using break
we can force the loop to exit, and using continue
we can force the loop to proceed to the next iteration without executing code in the loop body.