Java Reference
In-Depth Information
some situations where a two-dimensional array looks very much like an array of arrays.
For example, you will see that when using the instance variable
length
, you must
think of a two-dimensional array as an array of arrays.
Using the
length
Instance Variable
Suppose you want to fill all the elements in the following two-dimensional array with
'Z'
:
char
[][] page =
new char
[30][100];
You can use a nested
for
loop such as the following:
int
row, column;
for
(row = 0; row < page.length; row++)
for
(column = 0; column < page[row].length; column++)
page[row][column]
= 'Z';
Let's analyze this nested
for
loop in a bit more detail. The array
page
is actually a
one-dimensional array of length
30
, and each of the 30 indexed variables
page[0]
through
page[29]
is a one-dimensional array with base type
char
and with a length of
100
. That is why the first
for
loop is terminated using
page.length
. For a two-dimen-
sional array like
page
, the value of
length
is the number of first indices or, equiva-
lently, the number of rows—in this case,
30
. Now let's consider the inside
for
loop.
The
0
th
row in the two-dimensional array
page
is the one-dimensional array
page[0]
, and it has
page[0].length
entries. More generally,
page[row]
is a one-
dimensional array of
char
s, and it has
page[row].length
entries. That is why the
inner
for
loop is terminated using
page[row].length
. Of course, in this case,
page[0].length
,
page[1].length
, and so forth through to
page[29].length
are all
equal and all equal to
100
. (If you read the optional section entitled “Ragged
Arrays,” you will see that these need not all be equal.)
Self-Test Exercise
23. What is the output produced by the following code?
int
[][] myArray =
new
int
[4][4];
int
index1, index2;
for
(index1 = 0; index1 < myArray.length; index1++)
for
(index2 = 0;
index2 < myArray[index1].length; index2++)
myArray[index1][index2] = index2;
for
(index1 = 0; index1 < myArray.length; index1++)
{
for
(index2 = 0;
index2 < myArray[index1].length; index2++)
System.out.print(myArray[index1][index2] + " ");
System.out.println();
}