1Z0-803 · Question #153
Given the code fragment: 5. // insert code here 6. 7. arr[0] = new int[3]; 8. arr[0][0] = 1; 9. arr[0][1] = 2; 10. arr[0][2] = 3; 11. 12. arr[1] = new int[4]; 13. arr[1][0] = 10; 14. arr[1][1] = 20; 1
The correct answer is C. int [][] arr = new int[2][]; E. int [][] arr = new int[2][0];. The code initializes a jagged 2D array, where arr[0] and arr[1] are later assigned new int arrays of different lengths. The missing line must declare arr as a 2D array, ensuring it can hold references to these subsequent int[] objects.
Question
Options
- Aint [][] arr = null;
- Bint [][] arr = new int[2];
- Cint [][] arr = new int[2][];
- Dint [][] arr = new int[][4];
- Eint [][] arr = new int[2][0];
- Fint [][] arr = new int[0][4];
How the community answered
(33 responses)- A12% (4)
- B3% (1)
- C79% (26)
- F6% (2)
Why each option
The code initializes a jagged 2D array, where `arr[0]` and `arr[1]` are later assigned new `int` arrays of different lengths. The missing line must declare `arr` as a 2D array, ensuring it can hold references to these subsequent `int[]` objects.
`int [][] arr = null;` would compile, but accessing `arr[0]` or `arr[1]` before assigning a non-null array to `arr` itself would result in a `NullPointerException` at runtime.
`int [][] arr = new int[2];` is a compile-time error because when declaring a jagged array, if the second dimension's size is not specified, empty brackets `[]` must be used.
`int [][] arr = new int[2][];` correctly declares `arr` as an array capable of holding two `int` arrays. The inner arrays are initially `null`, which is valid, allowing subsequent assignments like `arr[0] = new int[3];` to replace these `null` references with newly allocated arrays.
`int [][] arr = new int[][4];` is a compile-time error because if the first dimension's size is omitted, the array must be initialized immediately with values (e.g., `{ {1}, {2,3} }`), not just a second dimension size.
`int [][] arr = new int[2][0];` also correctly declares `arr` as an array of two `int` arrays, each initialized to an empty `int` array. The subsequent assignments `arr[0] = new int[3];` and `arr[1] = new int[4];` then reassign these array elements to new, non-empty `int[]` objects, which is a valid operation.
`int [][] arr = new int[0][4];` would compile, but since the outer array `arr` has a length of zero, attempting to access `arr[0]` or `arr[1]` would result in an `ArrayIndexOutOfBoundsException` at runtime.
Concept tested: Java jagged array declaration and initialization
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Topics
Community Discussion
No community discussion yet for this question.