Java Reference
In-Depth Information
Above, we show array b as an object, assuming that some values have been
assigned to its elements: Row 0 consists of the values {2, 5, 4} ; row 1 , the val-
ues {1, 4, 8} .
The number 2 within the first pair of brackets of the new-expression on the
second line means that the array has two rows, numbered 0 and 1 . The number 3
within the second pair of brackets means that the array has three columns, num-
bered 0 , 1 , and 2 . Since the base type is int , each element is initialized to 0 .
The type, or class, of b is int [][] , so b contains either null or the name of
an object of this type. A value of type int [][] is an object that is a two-dimen-
sional array of int elements.
In general, any type (or class) may be used in place of int , and this type is
the type of the array elements. It is the base type . Further, any int expression that
yields a nonnegative number can be used between a pair of brackets; the expres-
sion within the first bracket pair gives the number of rows; the expression with-
in the second bracket pair gives the number of columns.
Referencing an array element
The notation b[1][2] references the element in row 1 column 2 of two-
dimensional array b. This is actually a variable, called a subscripted variable, so
it could be used in the left of an assignment to change the element. For example,
with b as shown above, the assignment statement:
b[1][2]= b[0][0] + 1;
changes array b to this:
2 5 4
1 4 3
b a0
In mathematics, the notation b r,c would be used to reference the element,
and many programming languages use the notation b[r, c] . Java has a reason
for using the notation b[r][c] , which will become clear in Sec. 9.3.
In an array-element reference like b[r][c] , r and c must satisfy:
0≤r<( number of rows in b)
0≤c<( number of columns in row r of b)
Referencing the number of rows and columns of b
The number of rows of rectangular array b is given by the expression
b.length . The number of columns in row i of b is given by b[i].length .
Actually, since the array is rectangular, so that all rows have the same number of
columns, the number of columns in any row is given by the expression
b[0].length . However, in Java, we prefer to reference the number of columns
in row i using b[i].length .
Search WWH ::

Custom Search