nerdexam
Oracle

1Z0-808 · Question #20

Given the following array: int[] intArr = {8, 16, 32, 64, 128}; Which two code fragments, independently, print each element in this array?

The correct answer is B. for (int i : intArr) { System.out.print (i + " "); } E. for (int i=0; i < intArr.length; i++) { System.out.print (intArr[i] + " "); }. B and E are correct because they each correctly retrieve the actual element values from the array. In B, the enhanced for-each loop (for (int i : intArr)) assigns each array value directly to i on every iteration, so printing i gives 8 16 32 64 128. In E, the traditional…

Using Loop Constructs

Question

Given the following array: int[] intArr = {8, 16, 32, 64, 128}; Which two code fragments, independently, print each element in this array?

Options

  • Afor (int i : intArr) { System.out.print (intArr[i] + " "); }
  • Bfor (int i : intArr) { System.out.print (i + " "); }
  • Cfor (int i=0 : intArr) { System.out.print (intArr[i] + " "); i++; }
  • Dfor (int i=0; i < intArr.length; i++) { System.out.print (i + " "); }
  • Efor (int i=0; i < intArr.length; i++) { System.out.print (intArr[i] + " "); }
  • Ffor (int i; i < intArr.length; i++) { System.out.print (intArr[i] + " "); }

How the community answered

(18 responses)
  • B
    89% (16)
  • D
    6% (1)
  • F
    6% (1)

Explanation

B and E are correct because they each correctly retrieve the actual element values from the array. In B, the enhanced for-each loop (for (int i : intArr)) assigns each array value directly to i on every iteration, so printing i gives 8 16 32 64 128. In E, the traditional for-loop uses i as an index (0–4), and intArr[i] correctly retrieves each element by position.

Why the distractors fail:

  • A - In a for-each loop, i holds the value (8, 16, 32…), so intArr[i] tries to access index 8, 16, etc., causing an ArrayIndexOutOfBoundsException.
  • C - for (int i=0 : intArr) is invalid syntax; the enhanced for-each loop does not support variable initialization with =.
  • D - Uses the correct traditional loop structure, but prints i (the index: 0 1 2 3 4) instead of intArr[i] (the values).
  • F - Declares i without initializing it; Java requires local variables to be initialized before use, causing a compile error.

Memory tip: Ask yourself "is i a value or an index?" - in a for-each loop i is the value (print it directly), while in a traditional for-loop i is an index (use it inside brackets).

Topics

#enhanced for loop#traditional for loop#array iteration#loop semantics

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice