1Z0-808 · Question #11
Given the code fragment: String[] strs = new String[2]; int idx = 0; for (String s : strs) { strs[idx].concat(" element " + idx); idx++; } for (idx = 0; idx < strs.length; idx++) {…
The correct answer is D. A NullPointerException is thrown at runtime. Option D is correct because new String[2] initializes both array slots to null by default, and calling .concat() on strs[idx] (which is null) at the first loop iteration immediately throws a NullPointerException - you cannot invoke instance methods on a null reference. A and B…
Question
Options
- AElement 0 Element 1
- BNull element 0 Null element 1
- CNull Null
- DA NullPointerException is thrown at runtime.
How the community answered
(28 responses)- A4% (1)
- B11% (3)
- C4% (1)
- D82% (23)
Explanation
Option D is correct because new String[2] initializes both array slots to null by default, and calling .concat() on strs[idx] (which is null) at the first loop iteration immediately throws a NullPointerException - you cannot invoke instance methods on a null reference.
A and B are wrong for two reasons: the NPE is thrown before any print statement is reached, and even if it weren't, String.concat() returns a new String rather than modifying the original - so strs[idx] would remain null regardless.
C is wrong because while printing null array elements would indeed output null twice, execution never reaches the second loop due to the NPE in the first loop.
Memory tip: Whenever you see an array created with new Type[n] and no explicit initialization, mentally tag every element as null - any method call on those elements is a guaranteed NPE waiting to happen. Also remember: String methods like concat, toUpperCase, and trim return new values; they never mutate in place.
Topics
Community Discussion
No community discussion yet for this question.