Page 409 - Introduction to Programming with Java: A Problem Solving Approach
P. 409
10.3 Array Declaration and Creation 375 The two formats are identical in terms of functionality. Most folks in industry prefer the first format, and that’s
what we use, but you should be aware of the alternative format in case you see it in someone else’s code.
Array Creation
An array is an object, albeit a special kind of object. As with any object, an array holds a group of data items. As with any object, an array can be created/instantiated using the new operator. Here’s the syntax for creating an array object with the new operator and assigning the array object into an array variable:
<array-variable> = new <element-type>[<array-size>];
The <element-type> indicates the type of each element in the array. The <array-size> indicates the number of elements in the array. The following code fragment creates a 10-element array of longs:
long[] phoneList;
phoneList = new long[10];
arraycreation
These two lines perform three operations: (1) The first line declares the phoneList variable, (2) the boxed code creates the array object, and (3) the assignment operator assigns a reference to the array object into the phoneList variable.
It’s legal to combine an array’s declaration, creation, and assignment operations into one statement. The following example does just that. It reduces the previous two-line code fragment to just one line:
long[] phoneList = new long[10];
Here, we use a constant (10) for the array’s size, but you’re not required to use a constant. You can use any expression for the array’sAsizpe.aFiguore 10.P3’sDSFpeedDEianlLhistaprongrcameprompts the user for the size of the array, stores the entered size in a sizeOfList variable, and uses sizeOfList for the array creation. Here’s the array creation code from the SpeedDialList program:
phoneList = new long[sizeOfList];
Array Element Initialization
Usually, you’ll want to declare and create an array in one place and assign values to your array elements in a separate place. For example, the following code fragment declares and creates a temperatures array in one statement, and assigns values to the temperatures array in a separate statement, inside a loop.
double[] temperatures = new double[5];
for (int i=0; i<5; i++)
declare and create array
assign a value to the ith array element
{
}
temperatures[i] = 98.6;
On the other hand, sometimes you’ll want to declare and create an array, and assign values to your array, all in the same statement. That’s called an array initializer. Here’s the syntax:
<element-type>[] <array-variable> = {<value1>, <value2>, . . ., <valuen>};
The code at the left of the assignment operator declares an array variable using syntax that you’ve seen before. The code at the right of the assignment operator specifies a comma-separated list of values that are assigned into the array’s elements. Note this example:
double[] temperatures = {98.6, 98.6, 98.6, 98.6, 98.6};