Java: Performing Basic Array Tasks - dummies

Java: Performing Basic Array Tasks

By John Paul Mueller

An array in Java is simply a list. It can be a list of anything — any primitive or object type. In most cases, an array is a list of like items. For example, if you create an int array, then all the items in that list are int values. The following sections describe how to create, initialize, iterate (examine each value), and otherwise manipulate arrays.

Defining an array

Always think of an array as a list of items. With this in mind, when you want to define an array, you begin with the type of the item you want to create. For example, if you want to create an array of integer values, you start with the int primitive type in most cases.

The type is followed by a pair of square brackets ([]), which is then followed by the array name. You often see an array defined for every Java application. The main() method declaration always includes one, as shown here:

public static void main(String[] args)

In this case, args is an array of type String. It contains the list of string values provided at the command line.

Initializing an array

Before you can use an array, you must initialize it. Initializing an array is a two-step process:

  1. Instantiate the array so that you have an array object to work with.

  2. Provide a value for each element in the array.

An array element is an individually accessible item in the list. Every element is a single item of the same type as the array. For example, when you define an int[] array, each element within the array is of type int.

The elements in an array are accessed using a unique number. The numbers begin at 0 and continue through one less than the total number of elements. For example, if you have an array with ten elements, they’re numbered from 0 through 9. To access a particular element, you use the array’s name, followed by the number enclosed in square brackets. The following code shows a typical array definition and initialization:

// Define an array of integer values.
int[] MyArray;
// Instantiate MyArray.
MyArray = new int[5];
// Define the individual array values.
MyArray[0] = 0;
MyArray[1] = 1;
MyArray[2] = 2;
MyArray[3] = 3;
MyArray[4] = 4;

This code creates an int[] array named MyArray. It instantiates this array to hold five entries by calling new int[5]. The code then initializes each of the individual array values by accessing the individual elements, 0 through 4.