Chapter 7 Arrays 317 7.3 (Hosting your own web site) Declaring and Allocating
Chapter 7 Arrays 317 7.3 Declaring and Allocating Arrays Arrays are objects that occupy space in memory. All objects in Java (including arrays) must be allocated dynamically with operator new. For an array, the programmer specifies the type of the array elements and the number of elements as part of the new operation. To allocate 12 elements for integer array c in Fig. 7.1, use the declaration int c[] = new int[ 12 ]; The preceding declaration also can be performed in two steps as follows: int c[]; // declares the array c = new int[ 12 ]; // allocates the array When allocating an array, each element of the array receives a default value zero for the numeric primitive-data-type elements, false for boolean elements or null for references (any nonprimitive type). Common Programming Error 7.2 Unlike array declarations in several other programming languages (such as C and C++), Java array declarations must not specify the number of array elements in the square brackets after the array name; otherwise, a syntax error occurs. For example, the declaration int c[ 12 ]; causes a syntax error. A program can allocate memory for several arrays with 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 ]; When declaring an array, the type of the array and the square brackets can be combined at the beginning of the declaration to indicate that all identifiers in the declaration represent arrays, as in double[] array1, array2; which declares both array1 and array2 as arrays of double values. As shown previously, the declaration and initialization of the array can be combined in the declaration. The following declaration reserves 10 elements for array1 and 20 elements for array2: double[] array1 = new double[ 10 ], array2 = new double[ 20 ]; A program can declare arrays of any data type. It is important to remember that every element of a primitive data type array contains one value of the declared data type. For example, every element of an int array contains an intvalue. However, in an array of a nonprimitive type, every element of the array is a reference to an object of the array s declared data type. For example, every element of a String array is a reference to a String. In arrays that store references, the references have the value null by default. 7.4 Examples Using Arrays This section presents several examples using arrays that demonstrate declaring arrays, allocating arrays, initializing arrays and manipulating array elements in various ways. For Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01