Arrays

Arrays can be declared in the following ways:

int[] a = new int[6];

This creates an array with six integer elements. The elements are indexed from 0 to 5 (not 1 to 6). You need to fill in the elements before trying to access them. Elements are accessed like this:

a[0] = 6;

Alternatively you can declare an array with an initialiser.

int[] a = { 1 , 2 , 3 };

You cannot combine the two ways of creating an array, i.e. you cannot declare the size and give the array an initialiser in the same statement.

Multi-dimensional arrays are used like this:

int[][] m = new int[5][5];
m[2][3] = 12;

or they can be declared like this, nesting the initialisers.


String[][] names = { { "john" , "phil" } , { "jones" , "smith" } }; 

To copy the contents of one array into another, use the arraycopy function.

int[] a = { 1 , 2 , 3 };
int[] b = { 7 , 8 , 9 };

arraycopy( b , a );

This code copies the elements of array b into the corresponing elements of array a. So both arrays will end up containing the numbers 7, 8, 9.