Break and continue Statements in Java
You will see questions related to the break
and continue
statements on the certification exam. The following exercise is somewhat difficult. However, if you can successfully work through the exercise questions, then you should do fine in the exam. If you miss one of the exam questions, make sure that you learn how the correct answer is obtained.
continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.
Consider the following class?
class Test{
public static void main(String[] args){
for (int i = 0; i < 10; i++) System.out.print(i + " "); //1
for (int i = 10; i > 0; i--) System.out.print(i + " "); //2
int i = 20; //3
System.out.print(i + " "); //4
}
}
Which of the following statements are true? [Select 4 options? ]
- As such the class will compile and print 20 in the end.
- It will not compile if line 3 is removed.
- It will not compile if line 3 is removed and placed before line 1.
- It will not compile if line 4 is removed and placed before line 3.
- Only Option 2, 3, and 4 are correct.
Answer: a, b, c, d
Explanation:
b. If //3 is removed, 'i' will be undefined for //4
The scope of a local variable declared in 'for' statement is the rest of the 'for' statement, including its own initializer.
So, when line 3 is placed before line 1, there is a re-declaration of i in the first for() which is not legal.
As such, the scope of i's declared in for() is just within the 'for' blocks.
So placing line 4 before line 3 will not work since 'i' is not in scope there.