Multi-Dimensional Arrays
There are no basic data constructs in Java for multi-dimensional arrays, but you can declare an array of arrays. The following program declares the Java equivalent of a two dimensional array, populates it and prints out the indices and the elements array. The elements are computed by multiplying 10 by the first index and adding the second index of each element.
Copy the following code into a
text editor and
save it as array2.java.
class array2 {
public static void main (String args[]){
int numbs2d[][] = new int[8][8];
for (int y = 0;y<8;y++)
{
System.out.println();
for (int x=0 ; x<8 ; x++)
{
numbs2d[x][y]=10*x+y;
System.out.print
("( "+x+","+y+") "+numbs2d[x][y]+" ");
}
}
}
}
|
Line 3 sets up an 8 X 8 array of integers Two nested loops are used (This drops down to a new line for each row) Populate the array(s) with integers and print the indices x,y ) and the element . |
After compiling this program run it by typing
java array2
This program needs no command line parameters.
The output should resemble the following.
0,0) 0 1,0) 10 2,0) 20 3,0) 30 4,0) 40 5,0) 50 6,0) 60 7,0) 70 0,1) 1 1,1) 11 2,1) 21 3,1) 31 4,1) 41 5,1) 51 6,1) 61 7,1) 71 0,2) 2 1,2) 12 2,2) 22 3,2) 32 4,2) 42 5,2) 52 6,2) 62 7,2) 72 0,3) 3 1,3) 13 2,3) 23 3,3) 33 4,3) 43 5,3) 53 6,3) 63 7,3) 73 0,4) 4 1,4) 14 2,4) 24 3,4) 34 4,4) 44 5,4) 54 6,4) 64 7,4) 74 0,5) 5 1,5) 15 2,5) 25 3,5) 35 4,5) 45 5,5) 55 6,5) 65 7,5) 75 0,6) 6 1,6) 16 2,6) 26 3,6) 36 4,6) 46 5,6) 56 6,6) 66 7,6) 76 0,7) 7 1,7) 17 2,7) 27 3,7) 37 4,7) 47 5,7) 57 6,7) 66 7,7) 77
Notice that the array indices start at 0,0 and finish at 7,6. The loops, as they are set up, do not use the full 8x8 array elements. The elements of the array reflect the indices. (e.g. the element at 2,5 is 2 * 10 + 5 or 25)
Even though Java does not support multi-dimensional arrays you can declare an array of arrays as we did in the example program for as many 'dimensions' as you need. Then you can access them as you would multi-dimensional arrays in C.
Go to the next topic: Searches and Sorts