Java Reference
In-Depth Information
The general syntax for declaring and instantiating an
n
-dimensional array is:
dataType[][]...[] arrayName
=
new
dataType[intExp1][intExp2] ... [intExpn];
where
intExp1
,
intExp2
, . . ., and
intExpn
are constant expressions yielding positive
integer values.
The syntax to access an element of an
n
-dimensional array is:
arrayName[indexExp1][indexExp2] ... [indexExpn]
where
indexExp1
,
indexExp2
,
...
, and
indexExpn
are expressions yielding nonnega-
tive integer values. Moreover, for each
i
, the value of
indexExpi
must be nonnegative
and less than the size of the
i
th dimension.
indexExpi
gives the position of the array
element in the
i
th dimension.
For example, the statement:
double
[][][] carDealers =
new double
[10][5][7];
declares
carDealers
to be a three-dimensional array. The size of the first dimension is
10
, the size of the second dimension is
5
, and the size of the third dimension is
7
. The
first dimension ranges from
0
to
9
, the second dimension ranges from
0
to
4
, and the
third dimension ranges from
0
to
6
. The base address of the array
carDealers
is the
address of the first array element—the address of
carDealers[0][0][0]
. The total
number of elements in the array
carDealers
is
10 * 5 * 7 = 350
.
The statement:
carDealers[5][3][2] = 15564.75;
sets the value of the element
carDealers[5][3][2]
to
15564.75
.
You can use loops to process multidimensional arrays. For example, the nested
for
loops:
for
(
int
i = 0; i < 10; i++)
for
(
int
j = 0; j < 5; j++)
for
(
int
k = 0; k < 7; k++)
carDealers[i][j][k] = 10.00;
initialize each element of the array to
10.00
.
During program execution, if an array index goes out of bounds, the program throws an
ArrayIndexOutOfBoundsException
. Exception handling is discussed in detail
in
Chapter 11.
Search WWH ::
Custom Search