next up previous
Next: Access to the single Up: Unit 07 Previous: Declaration of array variables

Creation of an array object

To use an array, we must first create it, by specifying the number of elements it should have.


Creation of an array object

Syntax:

new type[dimension]

where

Semantics:

Creates an array object with dimension elements of type type and returns a reference to the created object. The elements of the array are indexed from 0 to dimension-1 (see later), and each one is initialized to the default value for type.

Example:

int[] a;         // a is a variable of type array of integers
a = new int[5];  // creation of an array object with 5 elements
                 // or type int associated to the array variable a

After we have created an array object associated to an array variable, it is possible to access the single elements of the collection contained in the array. These elements are initialized to the default value for the type (for integers, it is 0, as illustrated in the figure).



next up previous
Next: Access to the single Up: Unit 07 Previous: Declaration of array variables