nerdexam
Oracle

1Z0-809 · Question #79

Given the code fragment: public class ForTest { public static void main(String[] args) { int[] arrar = {1,2,3}; for ( foo ) { } } } Which three are valid replacements for foo so that the program…

Three valid replacements are B, C, and A - though option A as printed likely contains a formatting error where the : (colon) was rendered as ; (semicolon). B (int i = 0; i < 1; i++) is the canonical for loop - all three sections present (init; condition; update) and…

Question

Given the code fragment: public class ForTest { public static void main(String[] args) { int[] arrar = {1,2,3}; for ( foo ) { } } } Which three are valid replacements for foo so that the program will compiled and run?

Options

  • Aint i; array
  • Bint i = 0; i < 1; i++
  • C;;
  • D; i < 1; i++
  • E; i;

Explanation

Three valid replacements are B, C, and A - though option A as printed likely contains a formatting error where the : (colon) was rendered as ; (semicolon).

B (int i = 0; i < 1; i++) is the canonical for loop - all three sections present (init; condition; update) and syntactically complete. C (;;) is valid because Java permits every section of a for loop to be empty; the missing condition defaults to true, producing an infinite loop that still compiles and runs. A is valid only when read as int i : array - the enhanced for-each syntax - which iterates over each element of the declared array; the colon was almost certainly mangled to a semicolon in typesetting.

D (; i < 1; i++) fails to compile because i is never declared anywhere in scope - skipping the init section doesn't magically create the variable. E (; i;) fails for the same reason (i is undeclared), and even if i were an int, Java (unlike C) does not allow a numeric expression as a boolean loop condition.

Memory tip: A regular for loop always needs exactly two semicolons separating three parts - any fewer is a syntax error. The enhanced for-each loop uses a colon, never a semicolon, and takes the form Type var : collection.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice