When many items of data of the same class or type have to be stored, it is more efficient to use an array than separate variables or objects.
For example, if the temperature on each day of the (non-leap) year had to be stored, rather than set up tempjan1, tempjan2... tempdec31 (365 variables) we would use the declaration:
The array variable tempArray stores 365 doubles, indexed from 0 to 364. Accessing the values in the array is done by using the index as follows:
Normally, arrays are processed using a for loop.
Example code
This is the code needed to find the average temperature for the year:
The above code uses the attribute ‘length’ of the array variable.
Initialising an array
The following line initialises the values and sets the size of an array to represent student grade values:
The array ‘grades’ has 5 elements, each a char(acter).
Arrays of objects
Consider
String[] words = new String[ 25 ];
The variable words holds 25 String references, but not the Strings themselves, which must be instantiated using ‘new’, eg:
words[0] = new String ("example text");
An array can be a formal parameter, as in:
... main ( String[] args) {
which is the method Java uses to pass command line parameter values into a program: args[0], args[1] etc.
For example, if the temperature on each day of the (non-leap) year had to be stored, rather than set up tempjan1, tempjan2... tempdec31 (365 variables) we would use the declaration:
Code: Java
double[] tempArray = new double[ 365 ];
The array variable tempArray stores 365 doubles, indexed from 0 to 364. Accessing the values in the array is done by using the index as follows:
Code: Java
tempArray[ 0 ] = 0.0;
lastDay = tempArray[ 364 ];
Example code
This is the code needed to find the average temperature for the year:
Code: Java
double total=0.0, average;
int size = tempArray.length;
for ( int index=0; index < size; index++) {
total += tempArray [ index ];
} // end for
average = total / size;
The above code uses the attribute ‘length’ of the array variable.
Initialising an array
The following line initialises the values and sets the size of an array to represent student grade values:
Code: Java
char[] grades = { 'A', 'B', 'C', 'D', 'E' };
The array ‘grades’ has 5 elements, each a char(acter).
Arrays of objects
Consider
String[] words = new String[ 25 ];
The variable words holds 25 String references, but not the Strings themselves, which must be instantiated using ‘new’, eg:
words[0] = new String ("example text");
An array can be a formal parameter, as in:
... main ( String[] args) {
which is the method Java uses to pass command line parameter values into a program: args[0], args[1] etc.

Table Students)