Java Reference
In-Depth Information
Creating and Accessing Arrays
In Java, an array is a special kind of object, but it is often more useful to think of an
array as a collection of variables all of the same type. For example, an array that
behaves like a collection of five variables of type
can be created as follows:
double
double [] score = new double [5];
This is like declaring the following to be five variables of type
:
double
indexed
variable
subscripted
variable
element
index,
subscript
length, size
score[0], score[1], score[2], score[3], score[4]
These individual variables that together make up the array are referred to in a variety
of different ways. We will call them
indexed variables
, though they are also some-
times called
subscripted variables
or
elements
of the array. The number in square
brackets is called an
index
or a
subscript
. In Java,
indices are numbered starting with
,
0
not
starting with
or any number other than
. The number of indexed variables in an
1
0
array is called the
of the array. When an array is created, the length of
the array is given in square brackets after the array name. The indexed variables are
then numbered (also using square brackets) starting with
length
or
size
and ending with the inte-
0
ger that is
one less than the length of the array.
The following
double [] score = new double [5];
is really shorthand for the following two statements:
double [] score;
score = new double [5];
The first statement declares the variable
to be of the array type
. The
score
double[]
second statement creates an array with five indexed variables of type
and makes
double
the variable
a name for the array. You may use any expression that evaluates to a
score
nonnegative
in square brackets. In particular you can fill a
variable with a value read from the keyboard and use the variable in place of the
value in place of the
int
5
. In
5
this way the size of the array can be determined when the program is run.
An array can have indexed variables of any type, but they must all be of the same
type. This type is called the
base type
base type
of the array. In our example, the base type of the
array
is
. To declare an array with base type
, simply use the type
score
double
int
name
when the array is declared and created. The base type of
an array can be any type. In particular it can be a class type.
Each of the five indexed variables of our example array
instead of
int
double
can be used just like
score
any other variable of type
. For example, all of the following are allowed in Java:
double
score[3] = 32;
score[0] = score[3] + 10;
System.out.println(score[0]);
The five indexed variables of our sample array
are more than just five plain
score
old variables of type
. That number in square brackets is part of the indexed
variable's name. So your program can compute the name of one of these variables.
double
Search WWH ::




Custom Search