1Z0-808 · Question #6
Given the code fragment: public class Test { public static void main(String[] args) { String[] arr = {"A", "B", "C", "D"}; for (int i = 0; i < arr.length; i++) { System.out.print (arr[i] + " "); if…
The correct answer is C. A Work done. There is an error in this question's stated answer. The actual correct answer is D. Compilation fails, not C. The break statement on the last line appears outside the for loop - the two closing braces } before System.out.println close the if block and the for loop respectively…
Question
Options
- AA B C Work done
- BA B C D Work done
- CA Work done
- DCompilation fails
How the community answered
(37 responses)- A11% (4)
- B3% (1)
- C78% (29)
- D8% (3)
Explanation
There is an error in this question's stated answer. The actual correct answer is D. Compilation fails, not C.
The break statement on the last line appears outside the for loop - the two closing braces } before System.out.println close the if block and the for loop respectively, leaving System.out.println("Work done") and break in the body of main with no enclosing loop or switch. In Java, break is only legal inside a loop (for, while, do-while) or a switch statement; using it anywhere else is a compile-time error.
Why the distractors fail:
- A and B assume the loop runs and prints output - impossible if the code won't compile.
- C ("A Work done") would only be valid if
printlnandbreakwere inside theforloop (after theifblock but before the loop's closing}). In that case, the first iteration prints"A ", skipscontinue(since"A" ≠ "C"), prints"Work done", and breaks. This is likely the scenario the question intended to test, but the brace counting in the code as written putsbreakoutside the loop.
Memory tip: Count braces carefully on exam questions - one misplaced } can turn a runtime question into a compilation question. Whenever you see break or continue, trace back to confirm it sits inside a valid enclosing loop or switch.
Bottom line for exam prep: If this appears on your exam as written, choose D. If the intended code has
printlnandbreakinside the loop, the answer would be C.
Topics
Community Discussion
No community discussion yet for this question.