Java multidimensional arrays (jagged): accessing an uninitialized inner array element. public class TestDogs { public static void main(String[] args) { Dog[][] theDogs = new Dog[3][]; // only outer dimension allocated System.out.println(theDogs[2][0].toString()); } } class Dog { }
-
Anull
-
BtheDogs
-
CCompilation fails
-
DAn exception is thrown at runtime
-
EEmpty output
Answer
Correct Answer: An exception is thrown at runtime
Explanation
Introduction / Context: Java supports jagged arrays, where only the outer dimension may be allocated initially. Inner arrays default to null until explicitly created. Attempting to index into a null inner array causes a NullPointerException at runtime.
Given Data / Assumptions:
- theDogs = new Dog[3][] allocates an array of length 3 whose elements are null references to Dog[].
- No inner arrays are assigned (e.g., theDogs[2] is null).
- Code accesses theDogs[2][0] and then calls toString() on it.
Concept / Approach: theDogs[2] is null; dereferencing it with [0] triggers NullPointerException before any call to toString() can occur. Compilation succeeds because the types are correct; failure occurs at runtime.
Step-by-Step Solution:
Allocate outer array → inner rows are null.Attempt index [2] → returns null reference for Dog[].Apply [0] to null → NullPointerException.Program terminates with an exception; no valid string is printed.Verification / Alternative check: Fix by allocating inner arrays: theDogs[2] = new Dog[1]; theDogs[2][0] = new Dog(); System.out.println(theDogs[2][0]);
Why Other Options Are Wrong:
- null / theDogs / Empty output: None match the thrown exception behavior.
- Compilation fails: Type-correct; compiles fine.
Common Pitfalls: Assuming both dimensions are allocated together; forgetting to new each inner row for jagged arrays.
Final Answer: An exception is thrown at runtime