Java Reference
In-Depth Information
pression (§
15.10
). The array creation expression specifies that the array should have
101
components. The length of the array is available using the field
length
, as shown.
The program fills the array with the integers from
0
to
100
, sums these integers, and
prints the result.
Arrays must be indexed by
int
values;
short
,
byte
, or
char
values may also be used as index
ues.
An attempt to access an array component with a
long
index value results in a compile-time
error.
All array accesses are checked at run time; an attempt to use an index that is less than zero
or greater than or equal to the length of the array causes an
ArrayIndexOutOfBoundsException
to be thrown.
10.5. Array Store Exception
For an array whose type is
A
[]
, where
A
is a reference type, an assignment to a component
of the array is checked at run time to ensure that the value being assigned is assignable to
the component.
ponent type, an
ArrayStoreException
is thrown.
If the component type of an array were not reifiable (§
4.7
), the Java Virtual Machine could
not perform the store check described in the preceding paragraph. This is why an array cre-
a variable of an array type whose element type is non-reifiable, but assignment of the result
of an array creation expression to the variable will necessarily cause an unchecked warning
Example 10.5-1.
ArrayStoreException
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
public static void main(String[] args) {
ColoredPoint[] cpa = new ColoredPoint[10];
Point[] pa = cpa;
System.out.println(pa[1] == null);