| Multi-dimensional arrays in Java are simply arrays of arrays.
Creating an array of arrays such as:
char lines[][] = new char[8][20];
produces the following:

What do you think
the following will print?
char lines[][] = new char[8][20];
System.out.println(
"char lines[][] has " + lines.length + " elements");
System.out.println(
"lines[0] has " + lines[0].length + " elements");
System.out.println(
"lines[0] contains: " + lines[0]);
What about the following?
char line[][] = new char[8][/* NOTHING */];
System.out.println(
"char line[][] has " + line.length + " elements");
System.out.println(
"line[0] has " + line[0].length + " elements");
System.out.println(
"line[0] contains: " + line[0]);
Note that, because Java multidimensional
arrays are arrays of arrays, they need not be 'rectangular'.
For example:
short triangle[][] = new short[10][];
for (int i = 0; i < triangle.length; i++)
{
triangle[i] = new short[i+1];
for (int j = 0; j < i+1; j++)
triangle[i][j] = (short)(i + j);
}
for (int i = 0; i < triangle.length; i++)
{
for (int j = 0; j < triangle[i].length; j++)
System.out.print(triangle[i][j] + " ");
System.out.println();
}
produces:
0
1 2
2 3 4
3 4 5 6
4 5 6 7 8
5 6 7 8 9 10
6 7 8 9 10 11 12
7 8 9 10 11 12 13 14
8 9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16 17 18
|