nerdexam
Oracle

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…

Arrays and Logic

Question

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) { System.out.print(x + " "); } System.out.println(""); for (int y: lst) { System.out.print(y + " "); } What is the result?

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)
  • A
    10% (3)
  • B
    7% (2)
  • C
    21% (6)
  • D
    62% (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 prints 10 20.
  • ArrayList (lst): Unlike arrays, ArrayList grows dynamically. lst.add(20) appends a third element, so the list becomes [10, 15, 20] and prints 10 15 20.
  • for (int y: lst) does compile - Java 5+ auto-unboxes Integer to int in 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 20 for the list, which ignores that lst.add(15) was called before lst.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

#arrays#ArrayList#enhanced-for-loops#type-compatibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice