Session 2 |
Arrays
Suppose that you want to find the average of the grades for a class of 30 students. Would you like to create 30 variables and manually calculate the average? A more elegant solution would be to use an array.
An array is an ordered collection of elements (either objects or primitives), all the same data type and packaged together under one identifier name. The values in the array are called elements. Unlike Python, the size of an array cannot be changed simply adding new elements into an array. In Java, the size of an array must be defined and fixed.
Arrays are objects, which means that they have to be constructed. To declare and initialize an array, we have to:
- declare the array with a name (generally in plural, e.g. grades, names, etc.), a data type (one for all elements in the array) and the square brackets indexing operator
[ ]
. - allocate the array using operator
new
, or initialization.
Example on arrays:
int[] grades; // declare an int array named grades // at this point we have a reference to an array // no space has been allocated for the array grades int grades2[]; // the same as above, but the above syntax recommended grades = new int[30]; // allocate 30 elements via operator "new" // the array contains 30 values of 0 (by default) // the values can be changed using indexes and assignments int[] grades3 = new int[20]; // the above two statements merged together // the array contains 20 values of 0 (by default) // the values can be changed using indexes and assignments int[] grades4 = {11, 22, 33, 44, 55, 66}; // declare and initialize an array // size of array deduced from the number of elements
We can refer to an element of an array via an index (or subscript) enclosed within the square bracket [ ]
. In Java, indexing starts from zero.
In Java, we need to known the length (or size) of the array in advance, and allocate accordingly. If we do not know the exact number of elements in the array, we still need to estimate the length and allocate an upper bound. Once an array is created, its length is fixed and cannot be changed.
In Java, the length of array is kept in an variable called length
and can be retrieved using arrayName.length
, e.g.:
int[] grades = new int[5]; // declare and allocate a 5-element int array int gradesSize = grades.length; // gradesSize is 5
The index of an array is between 0 and arrayName.length
- 1.
Arrays and Loops
If we try to print the values of an array using
System.out.println(grades);
the result will be something like [I@2471cca7
. This is because we ask Java to print the reference to the array, not its values. To print the values of an array, we have to use loops.
Arrays works hand-in-hand with loops. We can process all the elements of an array via a loop:
/* * Find the mean of the points kept in an array */ public class ArrayTest { public static void main(String[] args) { int[] points = {74, 43, 58, 60, 90, 64, 70}; int sum = 0; int count = points.length; double mean; for (int i = 0; i<count; i++) { sum += points[i]; } mean = (double)sum/count; System.out.printf("Mean is %.2f%n", mean); } }
Enhanced for-loop (or "for-each" Loop)
A new loop syntax known as enhanced for-loop (or for-each loop) facilitates processing of arrays and collections. It takes the following syntax:
for ( data_type item : myArray ) { //loop body; }
In such loops, the data_type must be of the same type as the array itself!
Example on the enhanced for-loop:
int[] myNumbers = {1,2,3,4,5,6,7,8,9}; int sum = 0; for (int i : myNumbers) { // for each int number in int[] numbers sum += i; } System.out.println("The sum is " + sum);
Session 2 |