nerdexam
Oracle

1Z0-808 · Question #73

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

The correct answer is A. int i: array B. int i=0;i<1;i++ C. Options A, B, and C are valid because Java supports two forms of the for loop: the enhanced for-each (for (int i : array) - option A), the traditional three-part loop (for (int i=0; i<1; i++) - option B), and crucially, all three parts of a traditional for loop are optional…

Using Loop Constructs

Question

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

Options

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

How the community answered

(50 responses)
  • A
    88% (44)
  • D
    4% (2)
  • E
    8% (4)

Explanation

Options A, B, and C are valid because Java supports two forms of the for loop: the enhanced for-each (for (int i : array) - option A), the traditional three-part loop (for (int i=0; i<1; i++) - option B), and crucially, all three parts of a traditional for loop are optional, making for (;;) (option C) a legal infinite loop that compiles and runs fine.

Options D and E fail because they reference the variable i (e.g., i<1 or i++) without ever declaring it. Since i is not declared anywhere in the method scope, the compiler throws an "cannot find symbol" error - leaving the initialization slot empty doesn't mean i magically exists.

Memory tip: Think of the traditional for as three optional slots separated by two mandatory semicolons - for( opt ; opt ; opt ). You can omit any or all of them, but you cannot reference variables that don't exist in the surrounding scope, which is the trap in D and E.

Topics

#for loops#enhanced for syntax#loop initialization#for-each

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice