Looping is an incredibly important feature of practically all programming languages, including Java. In fact, it is so important that Java supports no less that four types of loops: While, Do While, For, and For-each. We learned about the While and Do While loops in a previous tutorial. We then covered the For and For-each loops. You can out those two articles below:
Which ever loop you choose to employ for iterating over a collection or object properties, there may be times that you will need to terminate the loop immediately without checking the test expression, or skip some statements inside the loop. To do that, developers can use the break and continue statements. This programming tutorial will demonstrate how to use the break and continue statements in Java using code examples to help bring everything together.
The break Statement in Java
In Java, the break statement is used to terminate loop execution immediately. Hence, when a break statement is encountered inside a loop, the loop iteration stops there, and the control of the program moves to the next statement following the loop. The break statement is useful when programmers are not sure about the actual number of iterations they will need for the loop, or they want to terminate the loop based on some condition.
Most Java tutorials about loops and the break statement provide a rather contrived example, like the following loop that increments a variable on each iteration and breaks when the counter variable reaches a certain value:
for (int i = 0; i < 10; i++) { if (i == 5) { break; } System.out.println(i); } /*prints 0 1 2 3 4 */
Since the variable i is never going to hit 10 and exit the loop normally, the code could easily be rewritten without the break by setting the target i value to 4 instead of 10. Here is a more realistic example that introduces an element of unpredictability by accepting input from the user. The program takes a series of int values between 1 and 10, which it sums together. Should the user provide a number that falls outside of the specified range, the break statement is utilized to exit the loop and provide the sum at that point:
import java.util.Scanner; class BreakExample { public static void main(String[] args) { int number, sum = 0; Scanner input = new Scanner(System.in); while (sum < 10) { System.out.print("Please enter a whole number between 1 and 10: "); number = input.nextInt(); // if number is negative or zero the loop terminates if (number < 1 || number > 10) { System.out.println("You have entered an invalid number. Aborting."); break; } sum += number; } System.out.println("sum = " + sum); } }
Here is a screen shot that shows what a typical successful full run might look like:
Supplying a negative number would trigger the break statement, resulting in early termination and an error message:
Please enter a whole number between 1 and 10: 4 Please enter a whole number between 1 and 10: -1 You have entered an invalid number. Aborting. sum = 4
Using break With a Label in Java
When employed inside of nested loops, the break statement terminates the innermost loop only:
while (testEpression) { while (testEpression) { if (conditionToBreak) { break; } // more code } // execution continues here after break: // more code }
We can use the labeled break statement to terminate the outermost loop as well by placing a label above the loops. Here is a nifty program that searches through an array of int pairs and finds the first value of 10 or more. Once found, the break statement exits both loops and the results are presented to the user in the form of a detailed message:
class LabeledBreakExample { public static void main(String[] args) { int[][] arrIntPairs = { { 1, 2 }, { 3, 4 }, { 9, 10 }, { 11, 12 } }; boolean found = false; int row = 0; int col = 0; // found index of first int greater than or equal to 10 found: for (row = 0; row < arrIntPairs.length; row++) { for (col = 0; col < arrIntPairs[row].length; col++) { if (arrIntPairs[row][col] >= 10) { found = true; // using break label to terminate both loops break found; } } } if (found) System.out.println( "First int greater than 10 is found at index: [" + row + "," + col + "]: " ); } }
Here is the full program along with its produced output:
Read: Best Project Management Tools for Developers
The continue Statement in Java
Rather than exit the loop, the continue statement breaks one iteration of the loop and continues with the next loop iteration.
Here is the very first example that we saw today using a continue rather than break:
for (int i = 0; i < 10; i++) { if (i == 5) { continue; } System.out.println(i); } /*prints 0 1 2 3 4 6 7 8 9 */
Using continue makes more sense in this context because it does not nullify the loop test. We still want a total of 10 iterations, while only printing every value but 5.
Developers can refactor the BreakExample program above using the continue statement so that, instead of aborting when the user enters an invalid number value, we can simply ask for another:
import java.util.Scanner; class ContinueExample { public static void main(String[] args) { int number, sum = 0; Scanner input = new Scanner(System.in); while (sum < 10) { System.out.print("Please enter a whole number between 1 and 10: "); number = input.nextInt(); // if number is negative or zero the loop terminates if (number < 1 || number > 10) { System.out.println("You have entered an invalid number. Try again."); continue; } sum += number; } System.out.println("sum = " + sum); } }
Here is the updated program and output:
The Labeled continue Statement in Java
As of JDK 1.5, the continue statement may also be used with a label. It can be employed to skip the current iteration of an outer loop so that the program control goes to the next iteration of an inner loop. Here is a code example:
class LabeledContinueExample { public static void main(String[] args) { outer: for (int i = 1; i < 6; ++i) { // inner loop for (int j = 1; j < 5; ++j) { if (i == 3 || j == 2) // skips the current iteration of outer loop continue outer; System.out.println("i = " + i + "; j = " + j); } } } }
We can see in the program output below that the iteration of the outer for loop was skipped if either the value of i was 3 or the value of j was 2:
Final Thoughts on the Java Break and Continue Statements
In this programming tutorial, we learned how to use the Java break and continue statements, using several code examples that helped bring everything together.
Note that using the labeled continue statement tends to be discouraged because it can make your code hard to understand. If you ever find yourself in a situation where you feel the need to use labeled continue, try refactoring your code to perform the task in a different way while making the code as readable as possible.