Next page | Contents page |

Arrays

Declare an array of a base type or any class by using [ ]:

	int [] scores;    // of type int [] - "array of int"
	Person [] people; // of type Person []

Can also write int scores []; but that's less clear about the type, which is int [].

Later (or maybe as part of the declaration), allocate memory for the array by using the new operator (an array is in fact an object). You have to know how many elements there are going to be in the array at this stage:

	final int N_PUPILS = 12;
	scores = new int [N_PUPILS];	// Elements all 0
	people = new Person [N_PUPILS]; // Elements all null

In the last case, an array of objects, the objects to go in the array do not yet exist. Each object must be created (typically with new and its constructor) before it can be used:

	people [3] = new Person ("John", "Smith");

Once memory has been allocated for an array its elements can be used like any other variable just by giving an index value (always of type int, starting at 0):

	int total = 0;
	for (int idx = 0; idx < scores.length; idx++)
	{ total += scores [idx]; }
	float mean = (float) total / scores.length;
	// NB: Why (float)?

The JVM checks array bounds and "throws an exception" if an invalid index is given (C/C++ programmers note).

Arrays are objects, so there is no delete: the JVM decides when the array memory can be freed.

scores.length field is a read-only number of array elements - every array has a field called length. It is important to remember that for arrays this is a field, not a method (by contrast, String has a length () method).

Multi-dimensional arrays

Are implemented as arrays of arrays (of ...). This example also shows how to create and initialise an array in one go:

	int [] scores = { 1, 4, 2, 6 };

	String [][] responses = { {"Yes", "No"},
					 {"Ja", "Nein"}, {"Oui", "Non"} };

"Oui" is indexed as responses [2][0] ie, [row][col].

Alternatively the syntax could be as before:

	String [][] responses = new String [3][2];
	String [0][0] = "Yes";
	// ... etc, for all the elements

For arrays which can be resized, see java.util.ArrayList - we will see more about this later.

Next page | Contents page |