Instructions
Answer all questions to test your understanding of 2D and 3D arrays. Remember: The computer only understands 1D arrays! A 2D array is an array of arrays - an array of references where each reference points to a 1D array.
Part 1: 2D Arrays (Array of Arrays)
1
Multiple Choice
What does this declaration create? Think in terms of "array of arrays".
Declaration.java
1int[][] matrix = new int[3][4];
Understanding: Array of Arrays Structure
2
Code Tracing
Given this 2D array, what is the value of
arr[1][2]?
Access2D.java
1int[][] arr = { 2 {10, 20, 30, 40}, 3 {50, 60, 70, 80}, 4 {90, 100, 110, 120} 5};
Array of Arrays Structure
3
Fill in the Blank
Using the same array from Question 2, what is the value of
arr.length?
arr.length =
4
Fill in the Blank
Using the same array, what is the value of
arr[0].length?
arr[0].length =
5
Code Tracing
What is the output of this code?
LastElement.java
1int[][] arr = { 2 {1, 2, 3}, 3 {4, 5, 6} 4}; 5 6int lastRow = arr.length - 1; 7int lastCol = arr[lastRow].length - 1; 8 9System.out.println(arr[lastRow][lastCol]);
Part 2: Ragged Arrays (Proof of Array of Arrays!)
6
True / False
In Java, all "rows" in a 2D array must have the same number of elements.
Why Ragged Arrays Are Possible: Each 1D Array is Independent!
7
Code Tracing
What is the value of
ragged[2].length?
RaggedArray.java
1int[][] ragged = { 2 {1, 2}, // Row 0: 2 elements 3 {3, 4, 5, 6}, // Row 1: 4 elements 4 {7, 8, 9} // Row 2: 3 elements 5};
8
Code Tracing
Using the same ragged array, what is
ragged[1][3]?
Part 3: 3D Arrays (Array of 2D Arrays)
9
Multiple Choice
What does this declaration create?
ThreeDArray.java
1int[][][] cube = new int[2][3][4];
10
Code Tracing
What is the value of
building[1][0][2]?
Building3D.java
1int[][][] building = { 2 // Layer 0 3 { 4 {1, 2, 3}, 5 {4, 5, 6} 6 }, 7 // Layer 1 8 { 9 {7, 8, 9}, 10 {10, 11, 12} 11 } 12};
11
Fill in the Blank
Using the same building array, what is
building.length?
building.length =
12
Fill in the Blank
Using the same building array, what is
building[0][1].length?
building[0][1].length =
Part 4: Advanced Questions
13
Code Tracing
What is the output of this code?
SumDiagonal.java
1int[][] matrix = { 2 {1, 2, 3}, 3 {4, 5, 6}, 4 {7, 8, 9} 5}; 6 7int sum = 0; 8for (int i = 0; i < matrix.length; i++) { 9 sum += matrix[i][i]; 10} 11 12System.out.println(sum);
14
Code Tracing
What is the output of this code?
CountElements.java
1int[][] ragged = { 2 {1}, 3 {2, 3}, 4 {4, 5, 6} 5}; 6 7int count = 0; 8for (int i = 0; i < ragged.length; i++) { 9 count += ragged[i].length; 10} 11 12System.out.println(count);
15
True / False
A 2D array in Java is stored as a single contiguous block of memory (all elements next to each other).
Memory Layout: Why 2D Arrays Are NOT Contiguous
Your Results
0%
0 Correct
0 Incorrect