Java Reference
In-Depth Information
tained in the array. The number of elements that the array will hold is determined by size .
Since arrays are implemented as objects, the creation of an array is a two-step process.
First, you declare an array reference variable. Second, you allocate memory for the array,
assigning a reference to that memory to the array variable. Thus, arrays in Java are dynam-
ically allocated using the new operator.
Here is an example. The following creates an int array of 10 elements and links it to an
array reference variable named sample :
This declaration works just like an object declaration. The sample variable holds a refer-
ence to the memory allocated by new . This memory is large enough to hold 10 elements
of type int . As with objects, it is possible to break the preceding declaration in two. For
example:
In this case, when sample is first created, it refers to no physical object. It is only after the
second statement executes that sample is linked with an array.
An individual element within an array is accessed by use of an index. An index describes
the position of an element within an array. In Java, all arrays have zero as the index of their
first element. Because sample has 10 elements, it has index values of 0 through 9. To index
an array, specify the number of the element you want, surrounded by square brackets. Thus,
the first element in sample is sample[0] , and the last element is sample[9] . For example,
the following program loads sample with the numbers 0 through 9:
Search WWH ::




Custom Search