1Z0-808 · Question #97
Given: ``java public class Test2 { public static void main(String[] args) { int ar1[] = {2, 4, 6, 8}; int ar2[] = {1, 3, 5, 7, 9}; int ar3[] = ar1; for (int e2 : ar2) { System.out.print("" + e2); }…
The correct answer is A. 2 4 6 8. There is an error in the provided answer key - the correct answer is actually D, not A. The for-each loop for (int e2 : ar2) explicitly iterates over ar2, which holds {1, 3, 5, 7, 9}, printing each element in sequence: 13579. The assignment ar3[] = ar1 is a deliberate…
Question
public class Test2 {
public static void main(String[] args) {
int ar1[] = {2, 4, 6, 8};
int ar2[] = {1, 3, 5, 7, 9};
int ar3[] = ar1;
for (int e2 : ar2) {
System.out.print("" + e2);
}
}
}
What is the result?Options
- A2 4 6 8
- B2 4 6 8 9
- C1 3 5 7
- D1 3 5 7 9
- ECompilation fails
- FAn exception is thrown at runtime
How the community answered
(28 responses)- A93% (26)
- C4% (1)
- F4% (1)
Explanation
There is an error in the provided answer key - the correct answer is actually D, not A.
The for-each loop for (int e2 : ar2) explicitly iterates over ar2, which holds {1, 3, 5, 7, 9}, printing each element in sequence: 13579. The assignment ar3[] = ar1 is a deliberate distractor - ar3 is declared but never referenced again, making it irrelevant to the output. Choice A (2 4 6 8) would only be correct if the loop iterated over ar1 or ar3, which it does not. Choice B (2 4 6 8 9) incorrectly combines both arrays. Choice C (1 3 5 7) would only be correct if the loop stopped one element short of ar1's length (4 elements), which has no basis in the code. The code compiles and runs without error, ruling out E and F.
Memory tip: When a for-each loop uses a variable name like e2, the digit hints at which array it's pulling from - e2 iterates ar2. Always trace the loop's source array, not the arrays assigned nearby.
Topics
Community Discussion
No community discussion yet for this question.