LECTURE NOTES IN JAVA ARRAY
MULTI-DIMENSIONAL ARRAY
Two-Dimensional Array
- A collection of a fixed number of elements arranged in rows and columns(that is, in two dimensions),
wherein all the elements are of the same type.
Declaring Two-Dimensional array:
dataType[ ] [ ] arrayName
where dataType is the data type of the array elements.
Instantiating Two-Dimensional array:
arrayName = new dataType[intExp1][intExp2];
where intExp1 and intExp2 are expressions yielding positive integer
0.
0.0 0.0 0.0 0.0 values. The two expressions specify the number of rows and the number
0
of
columns, respectively, in the array.
0.
0.0 0.0 0.0 0.0
0
The preceding two statements can be combined into one
0.
0.0 0.0 0.0 0.0
statement as follows:
0
dataType[ ] [ ] arrayName= new dataType[intExp1]
0.
0.0 0.0 0.0 0.0
[intExp2];
0
0.
0.0 0.0 0.0 0.0
Example:
0
0.
0.0 0.0 0.0 0.0 double[ ][ ] sales = new double[5]
0
[5];
0.
0.0 0.0 0.0 0.0 sales of 5 rows and 5 columns
- declares a two-dimensional array
0
wherein every elements are of
type double initialized to the default
0.
0.0 0.0 0.0 0.0
values which is 0.0.
- as in one-dimensional array, rows 0
and columns are numbered 0-4.
0.
0.0 2.3 0.0 0.0
0
0
1
2
3 0. 4 0.0 0.0 0.0 0.0
0
0
2
3
11
2
15
5
25
20
4
73
4
11 18 14
ACCESSING ARRAY ELEMENTS
To access the elements of two-dimensional array, you need a pair of indices; one for the row position, and
one for the column position.
Syntax:
arrayName[indexExp1][indexExp2]
where indexExp1 and indexExp2 are expressions yielding non-negative integer values.
Example:
Sales[3][2] = 2.3
Suppose that:
int x=5, y=3;
0
1
2
3
4
Then the previous statement:
Sales[3][2] = 2.3
is equivalent to Sales[x][y]=2.3;
2-DIM ARRAY INITIALIZATION DURING DECLARATION
Two-dimensional array can be initialized when they are declared.
Example illustration:
int[ ][ ] board ={{2,3,1}, {15,5,25}, {20,4,7}, {11,18,14}};
0
1
2
3
2
Jclight09
JORDAN T. COLCOL
LECTURE NOTES IN JAVA ARRAY
Jclight09
JORDAN T. COLCOL