Multi-dimensional arrays

Figure 408. Multidimensional arrays Slide presentation Create comment in forum
int[][] matrix = new int[2][3];

for (int row = 0; row < 2; row++) {
  for (int col = 0; col < 3; col++) {
    matrix[row][col] = col + row;
  }
}
for (int row = 0; row < 2; row++) {
  System.out.println(Arrays.toString(matrix[row]));
}

Figure 409. Behind the scenes Slide presentation Create comment in forum
final int[][] matrix = new int[2][]; // Array containing two int arrays
matrix[0] = new int[3];              // first int array
matrix[1] = new int[3];              // second int array

Figure 410. Memory allocation Slide presentation Create comment in forum

exercise No. 139

2-dimensional arrays and .length Create comment in forum

Q:

  1. In Figure 384, “Safer: Using length you were advised to prefer .length rather than using hard coded int literals like e.g. 5. Replace the first loop's respective limits 2 and 3 accordingly.

    Tip

    The array has got constant dimension with respect to each row of values. You may thus choose either matrix[0] of matrix[1] as a representative.

  2. Replace the second loop by a for-each style loop.

    Tip

    matrix[0] and matrix[1] are of type int[].

A:

Two-dimensional arrays in Java are nested arrays of arrays. We thus choose appropriate data types:

final int[][] matrix = new int[2][3];

for (int row = 0; row < matrix.length ; row++) {
  for (int col = 0; col < matrix[row].length ; col++) {
    matrix[row][col] = col + row;
  }
}
for (final int[]  row : matrix) {
  System.out.println(Arrays.toString(row));
}

The «outer» array's dimension: This int[][] array is the visible entry point containing references to rows each being implemented as a «simple» int[] array.

All rows are having identical length. We could thus use either representative matrix[0].length or matrix[1].length as well. However choosing matrix[row].length also works in case of different row lengths.

The variable matrix is of type int[][]. Each matrix[row] entry thus represents a reference to an «ordinary» int[] array. So row iteration requires a loop variable of type int[].

exercise No. 140

External array and string exercises Create comment in forum

Q:

Solve all examples from the following sections: