1Z0-809 · Question #96
Given: public class MyFor1 { public static void main(String[] args) { int[] x = {6, 7, 8}; for (int i : x) { System.out.print(i + " "); i++; } } } What is the result?
The correct answer is A. 6 7 8. Option A is correct because Java's enhanced for-each loop assigns each array element to i as a local copy - System.out.print(i + " ") runs first, printing the original values 6 7 8, and then i++ increments only that local copy, which is immediately discarded before the next…
Question
Options
- A6 7 8
- B7 8 9
- C0 1 2
- D6 8 10
- ECompilation fails
How the community answered
(65 responses)- A77% (50)
- B3% (2)
- C12% (8)
- D6% (4)
- E2% (1)
Explanation
Option A is correct because Java's enhanced for-each loop assigns each array element to i as a local copy - System.out.print(i + " ") runs first, printing the original values 6 7 8, and then i++ increments only that local copy, which is immediately discarded before the next iteration.
Why the distractors fail:
- B (7 8 9): Would require
i++to execute before the print, but it comes after - and even then, only modifies a copy. - C (0 1 2): Confuses the loop variable with the array index; in a for-each loop,
iholds the value, not the position. - D (6 8 10): Would require
i++to carry over into the next iteration, but the loop variable is re-assigned from the array on each pass. - E (Compilation fails): The syntax is perfectly valid Java -
i++on anintinside a loop is legal, just ineffective here.
Memory tip: Think of a for-each loop variable as a "read-only snapshot" - you can read the array's value through it, but writing to it is like writing on a sticky note you immediately throw away. If you need to modify the original array, use a traditional index-based for loop.
Community Discussion
No community discussion yet for this question.