5.7. Loop statements: break and continue

[5.5] Use break and continue

Imagine that you’ve defined a loop to iterate through a list of managers, and you’re looking for at least one manager whose name starts with the letter D. You’d like to exit the loop after you find the first match, but how? You can do this by using the break statement in your loop.

Now imagine that you want to iterate through all the folders on your laptop and scan any files larger than 10 MB for viruses. If all those files are found to be OK, you want to upload them to a server. But what if you’d like to skip the steps of virus checking and file uploading for file sizes less than 10 MB yet still proceed with the remaining files on your laptop? You can! You’d use the continue statement in your loop.

In this section, I’ll discuss the break and continue statements, which you can use to exit a loop completely or to skip the remaining statements in a loop iteration. At the end of this section, I’ll discuss labeled statements.

5.7.1. The break statement

The break statement is used to exit—or break out of—the for, for-each, do, and do-while loops, as well as switch constructs. Alternatively, the continue statement can be used to skip the remaining steps in the current iteration and start with the next loop iteration.

The difference between these statements can be best demonstrated with an example. You could use the following code to browse and print all the values of a String array:

String[] programmers = {"Paul", "Shreya", "Selvan", "Harry"};
for (String name : programmers) {
    System.out.println(name);
}

The output of the preceding code is as follows:

Paul
Shreya
Selvan
Harry

Let’s modify the preceding code to exit the loop when the array value is equal to Shreya. Here’s the required code:

The output of the preceding code is as follows:

Paul

As soon as a loop encounters a break, it exits the loop. Hence, only the first value of this array—that is, Paul—is printed. As mentioned in the section on the switch construct, the break statement can be defined after every case in order for the control to exit the switch construct once it finds a matching case.

The preceding code snippets are depicted in figure 5.21, which shows the transfer of control upon execution of the break statement.

Figure 5.21. The flow of control when the break statement executes within a loop

When you use the break statement with nested loops, it exits the inner loop. The next Twist in the Tale exercise looks at a small code snippet to see how the control transfers when you use a break statement in nested for loops (answer in the appendix).

Twist in the Tale 5.4

Modify the code used in the previous example as follows. What is the output of this code?

String[] programmers = {"Outer", "Inner"};
for (String outer : programmers) {
    for (String inner : programmers) {
        if (inner.equals("Inner"))
            break;
        System.out.print(inner + ":");
    }
}

  1. Outer:Outer:
  2. Outer:Inner:Outer:Inner:
  3. Outer:
  4. Outer:Inner:
  5. Inner:Inner:

5.7.2. The continue statement

The continue statement is used to skip the remaining steps in the current iteration and start with the next loop iteration. Let’s replace the break statement in the previous example with continue and examine its output:

The output of the preceding code is as follows:

Paul
Selvan
Harry

As soon as a loop encounters continue, it exits the current iteration of the loop. In this example, it skips the printing step for the array value Shreya. Unlike the break statement, continue doesn’t exit the loop—it restarts with the next loop iteration, printing the remaining array values (that is, Selvan and Harry).

When you use the continue statement with nested loops, it exits the current iteration of the inner loop.

Figure 5.22 compares how the control transfers out of the loop and to the next iteration when break and continue statements are used.

Figure 5.22. Comparing the flow of control when using break and continue statements in a loop

5.7.3. Labeled statements

In Java, you can add labels to the following types of statements:

  • A code block defined using {}
  • All looping statements (for, enhanced for, while, do-while)
  • Conditional constructs (if and switch statements)
  • Expressions
  • Assignments
  • return statements
  • try blocks
  • throws statements

An example of a labeled loop is given here:

String[] programmers = {"Outer", "Inner"};
outer:
for (int i = 0; i < programmers.length; i++) {
}

You can’t add labels to declarations. The following labeled declaration won’t compile:

It’s interesting to note that the preceding declaration can be defined within a block statement, as follows:

Labeled break statements

You can use a labeled break statement to exit an outer loop. Here’s an example:

The output of the preceding code is

Outer:

When this code executes break outer;, control transfers to the line of text that marks the end of this block. It doesn’t transfer control to the label outer.

Labeled continue statements

You can use a labeled continue statement to skip an iteration of the outer loop. Here’s an example:

The output of the preceding code is

Paul
Paul
Paul
Paul
Note

Please use labels sparingly and only if they really seem to increase the readability of your code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.226.255