## Multi-dimensional arrays

No. 154

### 2-dimensional arrays and .length

Q:

1. In Figure 415, “Safer: Using length you were advised to favour .length over hard coded int values like e.g. 5. Replace the error prone limits 2 and 3 in Figure 439, “Two-dimensional arrays accordingly.

2. Replace the second loop in Figure 439, “Two-dimensional arrays 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[].

No. 155

### External array and string exercises

 Q: Solve all examples from the following sections: