Array

An array is a container object that holds a fixed number of values of a single type. The type can be either a primitive type or a reference type, so we could have (for example) an array of int or an array of String. The length of an array is fixed – it is determined when the array is created. Each item in an array is known as an element and is accessed by a numerical index, starting at 0, as shown in the following diagram:

Array

The following program, ArrayDemo (taken from the Oracle Java Tutorial), creates an array of integers, inserts some values into it and prints each value to standard output.

package arraydemo;
public class ArrayDemo {
    public static void main(String[] args) {
        // declares an array of integers
        int[] anArray;

        // allocates memory for 10 integers
        anArray = new int[10];

        // initialize first element
        anArray[0] = 100;
        // initialize second element
        anArray[1] = 200;
        // and so forth
        anArray[2] = 300;
        anArray[3] = 400;
        anArray[4] = 500;
        anArray[5] = 600;
        anArray[6] = 700;
        anArray[7] = 800;
        anArray[8] = 900;
        anArray[9] = 1000;

        System.out.println("Element at index 0: " + anArray[0]);
        System.out.println("Element at index 1: " + anArray[1]);
        System.out.println("Element at index 2: " + anArray[2]);
        System.out.println("Element at index 3: " + anArray[3]);
        System.out.println("Element at index 4: " + anArray[4]);
        System.out.println("Element at index 5: " + anArray[5]);
        System.out.println("Element at index 6: " + anArray[6]);
        System.out.println("Element at index 7: " + anArray[7]);
        System.out.println("Element at index 8: " + anArray[8]);
        System.out.println("Element at index 9: " + anArray[9]);
    }
}

We can see the array declaration near the start of the program:

int[] anArray;

An array declaration has two components: the array’s type and the array’s name. The type is written as type[], where type is the data type of the and the square brackets indicate that this variable holds an array. The size of the array is not part of its type, so the brackets are empty. Arrays of other types can be declared in a similar manner, for example:

byte[] anArrayOfBytes;
String[] anArrayOfStrings;

Next: 2D Array