nerdexam
Oracle

1Z0-811 · Question #65

Given the code fragment: String[] flowers = {"lotus", "lily", "rose", "jasmine"}; for (String c : flowers) { if (c.length() < 4) { continue; } System.out.print(c + " "); if (c.length() == 4) {…

The correct answer is D. lotus lily. Option D is correct because tracing through the loop reveals two iterations before it stops: "lotus" has length 5, so it passes the continue check (5 is not < 4), gets printed, then fails the break check (5 ≠ 4); "lily" has length 4, also passes the continue check (4 is not <…

Control Flow

Question

Given the code fragment: String[] flowers = {"lotus", "lily", "rose", "jasmine"}; for (String c : flowers) { if (c.length() < 4) { continue; } System.out.print(c + " "); if (c.length() == 4) { break; } } What is the result?

Options

  • Alotus jasmine
  • Blotus
  • CA compilation error occurs.
  • Dlotus lily

How the community answered

(30 responses)
  • A
    17% (5)
  • B
    3% (1)
  • C
    7% (2)
  • D
    73% (22)

Explanation

Option D is correct because tracing through the loop reveals two iterations before it stops: "lotus" has length 5, so it passes the continue check (5 is not < 4), gets printed, then fails the break check (5 ≠ 4); "lily" has length 4, also passes the continue check (4 is not < 4), gets printed, then triggers break because 4 == 4, ending the loop entirely before "rose" or "jasmine" are ever visited.

A (lotus jasmine) is wrong because the break on "lily" exits the loop immediately - "jasmine" is never reached. B (lotus) is wrong because break only triggers when c.length() == 4, and "lotus" has length 5, so the loop continues after printing it. C is wrong because the code is perfectly valid Java - enhanced for-loops with continue and break are legal.

Memory tip: Think of the two if blocks as a gate-and-exit pattern - the first if (< 4) is a skip gate (too short → skip via continue), and the second if (== 4) is an exit door (exactly 4 → print then leave via break). Walk each element through both checks in order and you'll never miss which ones print.

Topics

#break and continue statements#for-each loops#String.length()#loop execution tracing

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice