Arrays are useful when an ordered group of values need to be stored. The values should be of the same type (int, double, etc.) and there should be a fixed number of them, for example the entries of a vector or matrix. There are similarities in the behaviour of arrays and variables, but also some differences -- here is how to create an array that will contain entries that are of type double.
// way to create an array and fill with some numbers double[] vector1 = {1.2, 0.0, 5.3, 1.4}; // way to create an array but fill in values later double[] vector2; vector2 = new double[4]; // where 4 is the size (no. of entries)
This code creates the arrays {1.2, 0.0, 5.3, 1.4} called
vector1 and {0.0, 0.0, 0.0, 0.0} called vector2 -- note
that unlike a variable, if you do not specify initial values, all
entries are automatically initialised to zero. The first line in both
examples doesn't look unlike declaring a variable, and you can equally
well use other data types as desired, to get arrays of
integer values for example. The second line in both cases gives the
length or size of the array, for vector1 this is done by
explicitly giving the values of each element, in the case of
vector2 space is reserved for four values of type double
but the values will be filled in later in the code. As with variable
declarations the two lines of code can be reduced to one, e.g.
double[] vector2 = new double[4].
Figure 4.1 illustrates the creation of an array, which results in the values in the array occupying four adjacent words in the computer's memory. The array itself is a reference to this data.