Java Reference
In-Depth Information
Display 6.1
An Array Used in a Program
(part 2 of 2)
A Common Way to Visualize an Array:
Indices
0
1
2
3
4
80
99.9
75
100
85.5
score[3]
The array
score
The third use of square brackets is to name an indexed variable of the array, such as
score[0]
or
score[3]
, as illustrated by the following line:
max = score[0];
As we mentioned previously, the integer inside the square brackets can be any
expression that evaluates to a suitable integer, as illustrated by the following:
int
next = 1;
score[next + 3] = 100;
System.out.println(
"Score at position 4 is " + score[next + 3]);
Note that, in the preceding code,
score[next + 3]
and
score[4]
are the same
indexed variable, because
next
+
3
evaluates to
4
.
The
length
Instance Variable
In Java an array is considered to be an object, and, like other objects, it might
have instance variables. As it turns out, an array has only one public instance
variable, which is named
length
. The instance variable
length
is automatically set
to the size of the array when the array is created. For example, if you create an
array as follows,
double
[] score =
new
double
[5];
then
score.length
has a value of
5
.
The
length
instance variable can be used to make your program clearer by replac-
ing an unnamed constant, such as
5
, whose meaning may not be obvious, with a
meaningful name like
score.length
. In Display 6.2 we have rewritten the program in
Display 6.1 using the
length
instance variable.