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
values because they are subjected to unary numeric promotion (§ 5.6.1 ) and become int val-
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.
If the type of the value being assigned is not assignment-compatible (§ 5.2 ) with the com-
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-
ation expression with a non-reifiable element type is forbidden (§ 15.10 ) . One may declare
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
5.1.9 ) .
Example 10.5-1. ArrayStoreException
Click here to view code image
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);
Search WWH ::




Custom Search