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…
Question
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)- A8% (3)
- B83% (33)
- C5% (2)
- D3% (1)
- E3% (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). ValidString. - B does NOT compile:
new Integer(3)is anInteger, not aString. The compiler rejects adding anIntegerto anArrayList<String>. - C does NOT compile:
Integer.parseInt("3")returnsint(primitive), which also cannot be added to anArrayList<String>. - D compiles:
"three"is aString.
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
Community Discussion
No community discussion yet for this question.