Next: Accessing array elements. Up: Arrays. Previous: None.


The array type

Textbook: Section 5.1

An array is a sequence of several items. It gives us a way of having a single variable represent many similar items at once. This might, for example, be useful for representing students within a class, or components of a window, or files within a directory.

An array contains several items, all of the same type. Each item is called an element, and each element has a numeric address, called an index. The indices start at 0 and increase upward.

To declare an array variable, name the type of the array elements, followed by a pair of empty brackets, followed by the variable name.

int[] scores;
This creates a variable scores, which can hold an array of integers. Note that it doesn't actually hold an array yet - it just has the ability to hold an array. In this respect, arrays are like objects: We must explicitly create one before we use it. (Actually, the analogy extends further, as we will see later.)

Before you use an array you must create explicitly create it. We do this using the new keyword, as we did with objects.

scores = new int[30];
This makes scores point to an array of 30 integers.

As before, we can combine the variable declaration and initialization into one step.

int[] scores = new int[30];

If we happen to know exactly what we want in the array, we can list the items explicitly for initialization.

double[] pows = { 1.0, 0.5, 0.25, 0.125, 0.0625, 0.03125 };
This creates an array of six items, holding the named values.


Next: Accessing array elements. Up: Arrays. Previous: None.