Complete the Arrays of objects exercises before reviewing the solutions.
Review the Arrays of objects exercise 3 solution with AP CS Tutor Brandon Horn.
Original code
int[][] mat = new int[][] {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.deepToString(mat));
// prints:
// [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
int[] row = mat[1];
row[0] = 0;
System.out.println(Arrays.deepToString(mat));
Output
Arrays.deepToString
is a method to quickly produce formatted output. It is not covered on the AP CS A Exam. The format of the output below has been adjusted for readability.
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
[[1, 2, 3],
[0, 5, 6],
[7, 8, 9]]
Explanation
A 2D array is an array of 1D arrays. More precisely, a 2D array is an array of memory addresses of (references to) 1D arrays.
The statement int[] row = mat[1];
creates a variable named row
that stores the same memory address as mat[1]
.
The statement row[0] = 0;
changes the value at index 0
in the array to which row
refers to 0
. row
and mat[1]
refer to the same 1D array. The change affects the 2D array to which mat
refers.
Step by step memory diagram
Step 1
int[][] mat = new int[][] {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.deepToString(mat));
// prints:
// [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
// additional code not yet run
Memory diagram after Step 1
A 2D array is an array of 1D arrays. More precisely, a 2D array is an array of memory addresses of (references to) 1D arrays. mat[0]
stores the memory address of the array containing [1, 2, 3]
.
Output after Step 1
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Step 2
int[][] mat = new int[][] {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.deepToString(mat));
// prints:
// [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
int[] row = mat[1];
// additional code not yet run
Memory diagram after Step 2
mat[1]
stores the memory address of the array containing [4, 5, 6]
. The statement int[] row = mat[1];
creates a variable named row
that stores the same memory address as mat[1]
.
Step 3
int[][] mat = new int[][] {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.deepToString(mat));
// prints:
// [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
int[] row = mat[1];
row[0] = 0;
System.out.println(Arrays.deepToString(mat));
Memory diagram after Step 3
The statement row[0] = 0;
changes the value at index 0
in the array to which row
refers to 0
. row
and mat[1]
refer to the same 1D array. The change affects the 2D array to which mat
refers.
Output after Step 3
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
[[1, 2, 3],
[0, 5, 6],
[7, 8, 9]]