Creating Arrays

Arrays are variables grouped together under a common name. The term array should be familiar to you—think of a salesperson showing off her array of products or a game show with a dazzling array of prizes. Like variables, arrays are created by stating the type of variable being organized into the array and the name of the array. A pair of square brackets ([]) follow the type to distinguish arrays from variables.

You can create arrays for any type of information that can be stored as a variable. For example, the following statement creates an array of string variables:

String[] naughtyChild;

Here are two more examples:

int[] reindeerWeight;
boolean[] hostileAirTravelNations;

The previous examples create arrays, but they do not store any values in them. To do this, you can use the new keyword along with the variable type or store values in the array within { and } marks. When using new, you must specify how many different items are stored in the array. Each item in an array is called an element. The following statement creates an array and sets aside space for the values that it holds:

int[] elfSeniority = new int[250];

This example creates an array of integers called elfSeniority. The array has 250 elements that can store the months that each of Santa’s elves has been employed at the Pole. If Santa runs a union shop, this information is extremely important to track.

When you create an array with the new statement, you must specify the number of elements. Each element of the array is given an initial value that depends on the type of the array. All numeric arrays have the initial value 0, char arrays equal ‘’, and boolean arrays have the value false. A String array and all other objects are created with the initial value of null.

For arrays that are not extremely large, you can set up their initial values at the same time that you create them. The following example creates an array of strings and gives them initial values:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
    "Comet", "Cupid", "Donder", "Blitzen" };

The information that should be stored in elements of the array is placed between { and } brackets with commas separating each element. The number of elements in the array is set to the number of elements in the comma-separated list. Each element of the array must be of the same type. The preceding example uses a string to hold each of the reindeer names.

After the array is created, you cannot make room for more elements. Even if you recall the most famous reindeer of all, you couldn’t add “Rudolph” as the ninth element of the reindeerNames array. The Java compiler won’t let poor Rudolph join in any reindeerNames.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.176