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…
Question
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)- B89% (16)
- D6% (1)
- F6% (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,
iholds the value (8, 16, 32…), sointArr[i]tries to access index 8, 16, etc., causing anArrayIndexOutOfBoundsException. - 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 ofintArr[i](the values). - F - Declares
iwithout 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
Community Discussion
No community discussion yet for this question.