Chapter 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 an 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.
Examples on arrays:
int[] grades; // declare an int array with the name grades. // At this point we only have a reference to an array // no space in the memory has been allocated for the array yet. int grades[]; // Same as above, but the above syntax is 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[] grades = new int[30]; // The above two statements merged together // The array contains 30 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 // The size of the array is deduced from the number of elements
We can refer to an element of an array via its index (or subscript) enclosed within the square bracket [ ]
. Remember, 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 an array is kept in a variable called length
- therefore, no parenthesis are needed:
int[] grades = new int[5]; // declare and allocate a 5-element int array int gradesSize = grades.length; // gradesSize is 5
The indices in an array are between 0 and arrayName.length
- 1.
Arrays and Loops
If we try to print the elements of an array using the following statement
System.out.println(grades);
the result will be something like [I@2471cca7
. This is because in this way we ask Java to print the reference to the array, not its elements. To print the elements of an array, we have to use loops.
Arrays work hand-in-hand with loops. We can process all 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 arrays and collections. It takes the following syntax:
for ( data_type item : myArray ) { // loop body; }
In such loops, the data_type must be the same as the type of elements in the array!
An 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);
Chapter 2 |