Declaring and Creating Arrays
Array instances occupy space in memory. Like objects, arrays are created with keyword new. To create an array instance, you specify the type and the number of array elements and the number of elements as part of an array-creation expression that uses keyword new. Such an expression returns a reference that can be stored in an array variable. The following declaration and array-creation expression create an array object containing 12 int elements and store the array's reference in variable c:
int[] c = new int[ 12 ];
This expression can be used to create the array shown in Fig. 8.1 (but not the initial values in the arraywe'll show how to initialize the elements of an array momentarily). This task also can be performed in two steps as follows:
int[] c; // declare the array variable c = new int[ 12 ]; // create the array; assign to array variable
In the declaration, the square brackets following the variable type int indicate that c is a variable that will refer to an array of ints (i.e., c will store a reference to an array object). In the assignment statement, the array variable c receives the reference to a new array object of 12 int elements. When an array is created, each element of the array receives a default value0 for the numeric simple-type elements, false for bool elements and null for references. As we will soon see, we can provide specific, nondefault initial element values when we create an array.
|
An application can create several arrays in a single declaration. The following declaration reserves 100 elements for string array b and 27 elements for string array x:
string[] b = new string[ 100 ], x = new string[ 27 ];
In this declaration, string[] applies to each variable in the declaration. For readability, we prefer to declare only one variable per declaration, as in:
string[] b = new string[ 100 ]; // create string array b string[] x = new string[ 27 ]; // create string array x
|
An application can declare arrays of value-type elements or reference-type elements. For example, every element of an int array is an int value, and every element of a string array is a reference to a string object.
Examples Using Arrays
|