Java Reference
In-Depth Information
Notice that here board.length is 5 , the number of rows in the array board . Similarly,
board[0].length is 6 , the number of columns in the first row; board[1].length is 2 ,
the number of columns in the second row; board[2].length is 5 , the number of
columns in the third row; board[3].length is 3 , the number of columns in the fourth
row; and board[4].length is 4 , the number of columns in the fifth row.
Two-Dimensional Array Initialization during Declaration
Like one-dimensional arrays, two-dimensional arrays can be initialized when they are
declared. The example in the following statement helps illustrate this concept:
int [][] board = {{2, 3, 1},
{15, 25, 13},
{20, 4, 7},
{11, 18, 14}}; //Line 1
This statement declares board to be a two-dimensional array of 4 rows and 3 columns.
The elements of the first row are 2 , 3 , and 1 ; the elements of the second row are 15 , 25 ,
and 13 ; the elements of the third row are 20 , 4 , and 7 ; and the elements of the fourth row
are 11 , 18 , and 14 , respectively. Figure 9-19 shows the array board .
board
[0]
2
15
20
11
[1]
3
25
4
18
[2]
1
13
7
14
[0]
[1]
[2]
[3]
FIGURE 9-19 Two-dimensional array board
To initialize a two-dimensional array when it is declared:
￿ The elements of each row are enclosed within braces and separated by
commas.
￿ All rows are enclosed within braces.
Now consider the following statement:
int [][] table = {{2, 1, 3, 5},
{15, 25},
{4, 23, 45}};
Here, you see that the number of values specified for the first row of the array table is 4 ,
the number of values specified for the second row is 2 , and the number of values specified
for the third row is 3 . Because the number of values specified for the first row is 4 , only
 
Search WWH ::




Custom Search