Arrays

An array is a set of variables referenced by using a single variable name combined with an index number. Each item of an array is an element. All the elements in an array must be of the same type. Thus, the array itself has a type that specifies what kind of elements it can contain. An int array can contain int values, for example, and a String array can contain strings.

Written after the variable name, the index number is enclosed in brackets. So if the variable name is x, you could access a specific element with an expression like x[5].

tip.eps Index numbers start with 0 (zero) for the first element, so x[0] refers to the first element.

Declaring an array

Before you can create an array, you must declare a variable that refers to the array. This variable declaration should indicate the type of elements stored by the array, followed by a set of empty brackets, like this:

String[] names;

Here, a variable named names is declared. Its type is an array of String objects.

You can also put the brackets on the variable name rather than the type. The following two statements both create arrays of int elements:

int[] array1; // an array of int elements

int array2[]; // another array of int elements

Declaring an array doesn’t actually create the array. To do that, you must use the new keyword, followed by the array type. For example:

String[] names;

names = new String[10];

Or, more concisely: ...

Get Java For Dummies Quick Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.