# Declaring, Allocating and Initializing Two Dimensional Arrays

Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However you have to specify two dimensions rather than one, and you typically use two nested for loops to fill the array.

This example fills a two-dimensional array with the sum of the row and column indexes

class FillArray {

public static void main (String args[]) {

int[][] matrix;
matrix = new int[4][5];

for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
matrix[row][col] = row+col;
}
}

}

}
Of course the algorithm you use to fill the array depends completely on the use to which the array is to be put. The next example calculates the identity matrix for a given dimension. The identity matrix of dimension N is a square matrix which contains ones along the diagonal and zeros in all other positions.

class IDMatrix {

public static void main (String args[]) {

double[][] id;
id = new double[4][4];

for (int row=0; row < 4; row++) {
for (int col=0; col < 4; col++) {
if (row != col) {
id[row][col]=0.0;
}
else {
id[row][col] = 1.0;
}
}
}

}

}
In two-dimensional arrays ArrayIndexOutOfBoundsExceptions occur whenever you exceed the maximum column index or row index.

You can also declare, allocate, and initialize a a two-dimensional array at the same time by providing a list of the initial values inside nested brackets. For instance the three by three identity matrix could be set up like this:

double[][] ID3 = {
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0}
};
The spacing and the line breaks used above are purely for the programmer. The compiler doesn't care. The following works equally well:

double[][] ID3 = {{1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{0.0, 0.0, 1.0}};

Previous | Next | Top