Java Reference
In-Depth Information
A single variable of array type may contain references to arrays of different lengths, be-
cause an array's length is not part of its type.
If an array variable v has type A [] , where A is a reference type, then v can hold a reference
to an instance of any array type B [] , provided B can be assigned to A 5.2 ) . This may result
in a run-time exception on a later assignment; see § 10.5 for a discussion.
10.3. Array Creation
An array is created by an array creation expression (§ 15.10 ) or an array initializer (§ 10.6 ).
An array creation expression specifies the element type, the number of levels of nested ar-
rays, and the length of the array for at least one of the levels of nesting. The array's length
is available as a final instance variable length .
An array initializer creates an array and provides initial values for all its components.
10.4. Array Access
A component of an array is accessed by an array access expression (§ 15.13 ) that consists
of an expression whose value is an array reference followed by an indexing expression en-
closed by [ and ] , as in A[i] .
All arrays are 0 -origin. An array with length n can be indexed by the integers 0 to n -1.
Example 10.4-1. Array Access
Click here to view code image
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
This program produces the output:
5050
The program declares a variable ia that has type array of int , that is, int[] . The variable ia
is initialized to reference a newly created array object, created by an array creation ex-
Search WWH ::




Custom Search