nerdexam
Oracle

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…

Using Loop Constructs

Question

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 (arr[i].equals ("C")) { continue; } } System.out.println("Work done"); break; } } What is the result?

Options

  • AA B C Work done
  • BA B C D Work done
  • CA Work done
  • DCompilation fails

How the community answered

(37 responses)
  • A
    11% (4)
  • B
    3% (1)
  • C
    78% (29)
  • D
    8% (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 println and break were inside the for loop (after the if block but before the loop's closing }). In that case, the first iteration prints "A ", skips continue (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 puts break outside 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 println and break inside the loop, the answer would be C.

Topics

#for loops#continue/break statements#control flow#loop execution

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice