Java Reference
In-Depth Information
Java syntax: Subscripted variable
array
[
int
-
expression
]
Examples
:
b[5]= b[4] + 2;
Purpose
: To access an array element, to either retrieve its
value (as in
b[4]
) or change it (above,
b[5]
is changed).
the value
2
in
b[2]
is called the
subscript
, or
index
, of the array element. We call
b[2]
a
subscripted variable.
The
range
of an array is the set of values that can be used as indices. The
range of
b
consists of
0
,
1
,
2
, and
3
; we write this range as
0..3
.
The following statement stores the sum of
b[0]
and
b[1]
in variable
b[3]
:
b[3]= b[0] + b[1];
Any
int
expression can be used as an index. For example, if an
int
variable
x
has the value
5
,
b[x - 4]
refers to subscripted variable
b[1]
.
8.1.1
Declarations of arrays
Below, we show a declaration of an array:
int
[] b;
The notation
int
[]
is read as “
int
array”, and
b
's type is
int
[]
. Arrays are
objects. Just as the declaration:
String s;
does not create a
String
object,
b
's declaration does not create an array object.
It merely declares that variable
b
can
contain the name of an
int
array object.
Type
int
is called the
base type
of the array. Any type can be used as the
base type. Here is a declaration for an array of strings:
String[] s;
8.1.2
Creating an array
To create an array object and assign it to
b
, use a new-expression in an assign-
ment statement. The new-expression syntax is slightly different from other new-
expressions; no constructor is called. Here is an example:
b=
new int
[4];
Common error
. When using a subscripted variable
b[i]
, the value of
i
must be within the range
of
b
—one of the values
in 0..b.length - 1
. If
i
is not in range, an
IndexOut-
OfBoundsException
occurs and execution aborts. Get in the habit of always
asking yourself, with each variable
b[i]
you write, whether
i
is within range.
Search WWH ::
Custom Search