1Z0-808 · Question #78
Given the for loop construct: for ( expr1 ; expr2 ; expr3 ) { statement; } Which two statements are true?
The correct answer is A. This is not the only valid for loop construct; there exits another form of for loop constructor. B. The expression expr1 is optional. it initializes the loop and is evaluated once, as the loop begin. A is correct because Java (and C-style languages) also support the enhanced for-each loop (for (Type item : collection)), making the traditional three-part form not the only valid construct. B is correct because all three expressions in a for loop are optional - only the two…
Question
Options
- AThis is not the only valid for loop construct; there exits another form of for loop constructor.
- BThe expression expr1 is optional. it initializes the loop and is evaluated once, as the loop begin.
- CWhen expr2 evaluates to false, the loop terminates. It is evaluated only after each iteration through the loop.
- DThe expression expr3 must be present. It is evaluated after each iteration through the loop.
How the community answered
(25 responses)- A84% (21)
- C4% (1)
- D12% (3)
Explanation
A is correct because Java (and C-style languages) also support the enhanced for-each loop (for (Type item : collection)), making the traditional three-part form not the only valid construct. B is correct because all three expressions in a for loop are optional - only the two semicolons are mandatory, so for (; expr2; expr3) is perfectly valid.
C is wrong in its second clause: expr2 (the condition) is evaluated before each iteration, not after - it acts as the gate that decides whether the loop body runs at all, so it must be checked up front each cycle. D is wrong because expr3 is also optional; for (int i = 0;;) or even for (;;) (an infinite loop) are legal constructs, so "must be present" is false.
Memory tip: Think of the three expressions as Start, Stay, Step - all three are optional, but the two semicolons are not. If you can picture for (;;) as a valid infinite loop, you'll remember that none of the three expressions are mandatory.
Topics
Community Discussion
No community discussion yet for this question.