Java Reference
In-Depth Information
2.4.4
multidimensional arrays
Sometimes arrays need to be accessed by more than one index. A common
example of this is a matrix. A
multidimensional array
is an array that is
accessed by more than one index. It is allocated by specifying the size of its
indices, and each element is accessed by placing each index in its own pair of
brackets. As an example, the declaration
A
multidimensional
array
is an array
that is accessed by
more than one
index.
int [ ][ ] x = new int[ 2 ][ 3 ];
defines the two-dimensional array
x
, with the first index (representing the
number of rows) ranging from 0 to 1 and the second index (the number of col-
umns) ranging from 0 to 2 (for a total of six
int
s). Six memory locations are
set aside for these
int
s.
In the example above, the two-dimensional array is actually an array of
arrays. As such, the number of rows is
x.length
, which is 2. The number of
columns is
x[0].length
or
x[1].length
, both of which are 3.
Figure 2.9 illustrates how to print the contents of a two-dimensional
array. The code works not only for rectangular two-dimensional arrays,
but also for
ragged two-dimensional arrays,
in which the number of col-
umns varies from row to row. This is easily handled by using
m[i].length
at line 11 to represent the number of columns in row
i
. We also handle the
possibility that a row might be
null
(which is different than length 0), with
the test at line 7. The
main
routine illustrates the declaration of two-dimen-
sional arrays for the case where initial values are known. It is simply an
extension of the one-dimensional case discussed in Section 2.4.1. Array
a
is a straightforward rectangular matrix, array
b
has a
null
row, and array
c
is ragged.
2.4.5
command-line arguments
Command-line arguments are available by examining the parameter to
main
.
The array of strings represents the additional command-line arguments. For
instance, when the program is invoked,
Command-line
arguments
are
available by
examining the
parameter to
main
.
java Echo this that
args[0]
references the
String "this"
and
args[1]
references the
String "that"
.
Thus the program in Figure 2.10 mimics the standard
echo
command.
Search WWH ::
Custom Search