Page 407 - Introduction to Programming with Java: A Problem Solving Approach
P. 407

                Be aware that some people use the term “subscript” rather than “index” because subscripting is the standard English way to represent an element from within a group. In other words, x0, x1, x2, and so on in ordinary writing is the same as x[0], x[1], x[2], and so on in Java.
Example Program
Let’s see how arrays are used within the context of a complete program. In Figure 10.3, the SpeedDialList program prompts the user for the number of speed-dial phone numbers that are to be entered, fills up the phoneList array with user-entered phone numbers, and prints the created speed-dial list. To fill an array and to print an array’s elements, you typically need to step through each element of the array with the help of an index variable that increments from zero to the index of the array’s last filled element. Often, the index variable’s increment operations are implemented with the help of a for loop. For example, the SpeedDial- List program uses the following for loop header to increment an index variable, i:
for (int i=0; i<sizeOfList; i++)
With each iteration of the for loop, i goes from 0 to 1 to 2, and so on, and i serves as an index for the dif- ferent elements in the phoneList array. Here’s how the loop puts a phone number into each element:
phoneList[i] = phoneNum;
10.3 Array Declaration and Creation
In the previous section, wAe sphowaegd you hoPwDtoFperfoErmnsihmpalenopceraetiorns on an array. In so doing, we fo- cused on accessing an array’s elements. In this section, we focus on another key concept—declaring and creating arrays.
Array Declaration
An array is a variable and, as such, it must be declared before you can use it. To declare an array, use this syntax:
<element-type>[] <array-variable>;
The <array-variable> is the name of the array. The empty square brackets tell us that the variable is defined to be an array. The <element-type> indicates the type of each element in the array—int, double, char, String, and so on.
Here are some array declaration examples:
double[] salaries;
String[] names;
int[] employeeIds;
The salaries variable is an array whose elements are of type double. The names variable is an array whose elements are of type String. And finally, the employeeIds variable is an array whose elements are of type int.
Java provides an alternative declaration format for arrays, where the square brackets go after the vari- able name. Here’s what we’re talking about:
10.3 Array Declaration and Creation 373
 double salaries[];















































































   405   406   407   408   409