1Z0-811 · Question #40
Given the code fragment: int[] num = new int[2]; num[0] = 10; num[1] = 15; List<Integer> lst = new ArrayList<>(2); lst.add(10); lst.add(15); num[1] = 20; lst.add(20); for (int x: num) {…
The correct answer is D. A compilation error occurs. Option D is likely incorrectly marked as the answer here - this code compiles and runs without error in Java 5+. The actual output would be: `` 10 20 10 15 20 ` Making option A the correct answer. Here is why: Array (num): Fixed size of 2. num[1] is updated from 15 to 20, so…
Question
Options
- A10 20 10 15 20
- BA runtime exception is thrown.
- C10 20 10 20
- DA compilation error occurs.
How the community answered
(29 responses)- A10% (3)
- B7% (2)
- C21% (6)
- D62% (18)
Explanation
Option D is likely incorrectly marked as the answer here - this code compiles and runs without error in Java 5+. The actual output would be:
10 20
10 15 20
Making option A the correct answer. Here is why:
- Array (
num): Fixed size of 2.num[1]is updated from 15 to 20, so the loop prints10 20. - ArrayList (
lst): Unlike arrays,ArrayListgrows dynamically.lst.add(20)appends a third element, so the list becomes[10, 15, 20]and prints10 15 20. for (int y: lst)does compile - Java 5+ auto-unboxesIntegertointin enhanced for loops, so no compilation error occurs there.new ArrayList<>(2)sets the initial capacity (not size) to 2, which is perfectly legal.
Why the distractors are wrong:
- B (runtime exception): No null elements or index-out-of-bounds situations exist; everything is well-formed.
- C: Shows
10 20for the list, which ignores thatlst.add(15)was called beforelst.add(20)- the list holds all three values. - D: There is no compilation error; the code is syntactically and semantically valid Java.
Memory tip: Arrays have a fixed size - assignment replaces a value. ArrayList is dynamic - add() always appends, never replaces. When you see both in a question, count operations carefully: every add() grows the list, every arr[i] = overwrites in place.
Note to exam takers: If this question appears on your actual exam with D marked correct, it may be an error in the question bank. I'd recommend flagging it, as standard Java behavior clearly produces output A.
Topics
Community Discussion
No community discussion yet for this question.