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);
}
[5.5] Use break and continue
365 Loop statements: break and continue
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:
String[] programmers = {"Paul", "Shreya", "Selvan", "Harry"};
for (String name : programmers) { if (name.equals("Shreya")) break;
System.out.println(name);
}
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 con- struct, 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.
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).
Break out of the loop
for (String name : programmers) { System.out.println(name);
}
for (String name : programmers) { if (name.equals("Shreya"))
break;
System.out.println(name);
}
No exit condition. Code executes for all iterations offorloop.
Control is transferred here ifname is equal toShreya.
Figure 5.21 The flow of control when the break statement executes within a loop
366 CHAPTER 5 Flow control
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 + ":");
} }
a Outer:Outer:
b Outer:Inner:Outer:Inner:
c Outer:
d Outer:Inner:
e 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 previ- ous example with continue and examine its output:
String[] programmers = {"Paul", "Shreya", "Selvan", "Harry"};
for (String name : programmers) { if (name.equals("Shreya")) continue;
System.out.println(name);
}
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 itera- tion 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.
Twist in the Tale 5.4
Skip the remaining loop statements
367 Loop statements: break and continue
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:
outer :
int[] myArray = {1,2,3};
It’s interesting to note that the preceding declaration can be defined within a block statement, as follows:
outer : { int[] myArray = {1,2,3};
} for or while loop {
break;
}
Takes control here
break statement continue statement
Takes control to the start of next iteration
......
for or while loop {
continue;
}
......
Figure 5.22 Comparing the flow of control when using break and continue statements in a loop
Variable declaration that fails compilation
Start definition of block
Variable declaration, compiles
End block
368 CHAPTER 5 Flow control
LABELEDBREAKSTATEMENTS
You can use a labeled break statement to exit an outer loop. Here’s an example:
String[] programmers = {"Outer", "Inner"};
outer:
for (String outer : programmers) { for (String inner : programmers) { if (inner.equals("Inner"))
break outer;
System.out.print(inner + ":");
} }
The output of the preceding code is
Outer:
When this code executes breakouter;, control transfers to the line of text that marks the end of this block. It doesn’t transfer control to the label outer.
LABELEDCONTINUESTATEMENTS
You can use a labeled continue statement to skip an iteration of the outer loop.
Here’s an example:
String[] programmers = {"Paul", "Shreya", "Selvan", "Harry"};
outer:
for (String name1 : programmers) { for (String name : programmers) { if (name.equals("Shreya")) continue outer;
System.out.println(name);
} }
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.