Java Reference
In-Depth Information
The preceding two statements can be combined into one statement, as follows:
dataType[][] arrayName =
new
dataType[intExp1][intExp2];
For example, the statement:
double
[][] sales =
new double
[10][5];
declares a two-dimensional array
sales
of
10
rows and
5
columns, wherein every element is
of type
double
initialized to the default value of
0.0
. As in a one-dimensional array, the
rows are numbered
0...9
and the columns are numbered
0...4
(see Figure 9-16).
sales
[0] [1] [2] [3] [4]
[0]
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0
[1]
[2]
[3]
[4]
[5]
[6]
0.0 0.0 0.0
0.0
0.0
0.0 0.0 0.0
0.0
0.0
[7]
0.0 0.0 0.0
0.0
0.0
[8]
0.0 0.0 0.0
0.0
0.0
[9]
0.0 0.0 0.0
0.0
0.0
9
Two-dimensional array
sales
FIGURE 9-16
From this point forward, whenever we instantiate a two-dimensional array and draw its
diagram, all the default values may not be shown as they are in Figure 9-16.
To access the elements of a two-dimensional array, you need a pair of indices: one for the
row position, and one for the column position.
The syntax to access an element of a two-dimensional array is:
arrayName[indexExp1][indexExp2]
where
indexExp1
and
indexExp2
are expressions yielding nonnegative integer values.
indexExp1
specifies the row position and
indexExp2
specifies the column position. More-
over, the value of
indexExp1
must be nonnegative and less than the number of rows, and the
value of
indexExp2
must be nonnegative and less than the number of columns in the array.
Search WWH ::
Custom Search