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 it as
a collection of variables all of the same type. For example, an array that behaves like a
collection of five variables of type
double
can be created as follows:
double
[] score =
new double
[5];
This is like declaring the following to be five variables of type
double
:
indexed
variable
score[0], score[1], score[2], score[3], score[4]
The individual variables that make up the array are referred to in a variety of different
ways. We will call them
indexed variables
, though they are also sometimes 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
any
number
. The number of indexed variables in an array is called the
length
or
size
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
0
and ending with the integer that is
one less than the length of the array
.
The following example:
subscripted
variable
element
index,
subscript
length, size
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
score
to be of the array type
double[]
. The
second statement creates an array with five indexed variables of type
double
and makes
the variable
score
a name for the array. You may use any expression that evaluates to
a nonnegative
int
value in place of the
5
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
5
. In
this way, the size of the array can be determined when the program is run.
An array can have indexed variables of any type, as long as they are all of the same
type. This type is called the
base type
of the array. In our example, the base type of
the array
score
is
double
. To declare an array with base type
int
, simply use the type
name
int
instead of
double
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
score
can be used just like
any other variable of type
double
. For example, all of the following are allowed in Java:
base type
score[3] = 32;
score[0] = score[3] + 10;
System.out.println(score[0]);
The five indexed variables of our sample array
score
are more than just five plain
old variables of type
double
. 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.