int a[][] = new int[10][20];It can be initialised by code such as
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = 0;
}
}
The elements are accessed as a[i][j]. This is a consistent
notation since a[i][j] is element j of the array a[i]. This element is said to be in row i and column j. Note that a.length has the value 10 and each a[i].length has the value 20.
Two-dimensional arrays can, of course, be square e.g.
int a[][] = new int[10][10];They can also have different numbers of columns in each row. For example, the following code declares a (lower) triangular array in which row a[i] has i+1 elements.
int a[][] = new int[10][];
for (int i = 0; i < a.length; i++) {
a[i] = new int[i+1];
}
Such arrays can be useful for representing symmetric matrices,
a[i][j] == a[j][i], where it is only necessary to operate on, and store, one copy of the
off-diagonal elements. The following code initialises such an array
to the unit matrix, with 1's on the diagonal and 0's
elsewhere:
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < i; j++) {
a[i][j] = 0;
}
a[i][i] = 1;
}
The result is1 0 1 0 0 1if a.length == 3.
Multi-dimensional arrays can also be created and initialised using initialiser lists as in
int a[][] = {{54, 64}, {98, 12, 67}};