nerdexam
Oracle

1Z0-819 · Question #130

Which of the following options can be added to line 4 for the code to compile correctly? Given: var list = new ArrayList<String>(); list.add("one"); list.add("two"); //line 4 for (var s : list) {…

The correct answer is B. list.add(new Integer(3)). There appears to be an error in the answer key - B is actually incorrect, and the real correct answers are A and D. Here's why: list is declared as ArrayList<String>, so list.add() only accepts String arguments. Generics are enforced at compile time. A compiles…

Working with Arrays and Collections

Question

Which of the following options can be added to line 4 for the code to compile correctly? Given: var list = new ArrayList<String>(); list.add("one"); list.add("two"); //line 4 for (var s : list) { System.out.print(s); }

Options

  • Alist.add("String.valueOf(3)");
  • Blist.add(new Integer(3));
  • Clist.add(Integer.parseInt("3"));
  • Dlist.add("three");
  • ENone of these.

How the community answered

(40 responses)
  • A
    8% (3)
  • B
    83% (33)
  • C
    5% (2)
  • D
    3% (1)
  • E
    3% (1)

Explanation

There appears to be an error in the answer key - B is actually incorrect, and the real correct answers are A and D.

Here's why:

list is declared as ArrayList<String>, so list.add() only accepts String arguments. Generics are enforced at compile time.

  • A compiles: "String.valueOf(3)" is a string literal (the method call is never evaluated - it's just characters between quotes). Valid String.
  • B does NOT compile: new Integer(3) is an Integer, not a String. The compiler rejects adding an Integer to an ArrayList<String>.
  • C does NOT compile: Integer.parseInt("3") returns int (primitive), which also cannot be added to an ArrayList<String>.
  • D compiles: "three" is a String.

Since both A and D compile, and they're presented as separate single choices, the best standalone answer is D - it's the most straightforward. E ("None of these") is wrong because valid options exist.

Memory tip: When you see generics like ArrayList<String>, mentally replace every .add() call with "does this argument satisfy instanceof String?" - if not, it's a compile error. Don't be tricked by string-looking expressions like "String.valueOf(3)" - those quotes make it a literal string, not a method call.

Recommendation: Flag this question to your instructor - the answer key lists B as correct, but B would cause a compile-time type error on any standard Java compiler.

Topics

#generics#type safety#ArrayList#type checking

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice