Lesson 5 | The break and continue Statements |
Objective | Cover important points about the break and continue Statements in Java |
Java break Statement
Break Continue Statements
The
break
statement is used to transfer flow of control out of a statement, referred to as an
enclosing statement[1]. The execution of the enclosing statement is then terminated. The
break
statement may take an optional label. If no label is used, then the enclosing statement is the innermost loop (
for
,
while
, or
do
) or
switch
statement that contains the
break
statement. If a label is used, then the enclosing statement is the statement that contains the break statement and has the specified label. More than one statement in a method may have the same label as long as a statement does not enclose another statement with the same label.
Java continue Statement
The
continue
statement is similar to the
break
statement in that it affects the execution of an enclosing statement. However, the
continue
statement differs from the
break
statement in the following important ways:
- The
continue
statement is used with the for
, while
, and do
statements, but not the switch
statement.
- The
continue
statement only terminates the current loop iteration, not the loop.
When a
continue
statement is encountered, the execution of the innermost enclosing loop (or enclosing loop with matching label) is terminated. Control returns to the loop statement to determine whether the next iteration of the loop should take place.
- continue;
- continue label;
Object Java Reference
What will the following code print when run?
public class TestClass {
public static void main(String[] args) throws Exception {
String[] sa = { "a", "b", "c" };
for (String s : sa) {
if ("b".equals(s))
continue;
System.out.println(s);
if ("b".equals(s))
break;
System.out.println(s + " again");
}
}
}
Select 1 option:
- a
a again
c
c again
- a
a again
b
- a
a again
b
b again
- c
c again
Answer: 1
Explanation:
To determine the output you have to run through the loop one iteration at a time in your mind:
Iteration 1: s is "a". It is not equal to "b" so, it will print "a", and then "a again".
Iteration 2: s is "b". It is equal to "b", so the first if will execute "continue", which mean the rest of the code in the loop will not be executed (thus b and b again will not be printed), and the next iteration will start. Note that the second if is not executed at all because of the continue in the first if.
Iteration 3: s is "c", both the if conditions are not satisfied. So "c" and "c again" will be printed.
Two Dimensional Array loop Search - Exercise
[1] Enclosing statement: A statement, such as a switch, if, or loop statement, that contains the statement block of the statement in question.