CS115 lecture notes, Spring 1999 Week 11, Monday Hand back exams. Reading: Chapter 10 Warning: lots of errors in this Chapter. Quiz Wednesday on arrays. Arrays ------ An array is a set or collection of values, sort of like an objects, except: All the values have the same type. The values are indicated by number, rather than name. For every primitive type, there is a corresponding array type: int int[] (array of int) double double[] (array of double) You can declare array variables in the usual way: int[] count; double[] doubleArray; Just as with objects, these declarations create references to arrays. To allocate space for the array itself, you have to use the new command: count = new int[4]; doubleArray = new double[size]; The number in the square brackets is the size of the array. It can be any integer expression. By default, the elements of the array are initialized to zero. Elements of an array -------------------- The elements are numbered from zero. count[0] = 7; count[1] = count[0] * 2; count[2]++; count[3] = count[3] - 60; You can use any integer expression as an index. If you use an index that is negative or >= size, you get an ArrayOutOfBoundsException. You can use loops to traverse arrays: int i = 0; while (i<4) { System.out.println (count[i]); i++; } Example: Given an array of doubles, a, how would you make a copy? double[] a = new double[3]; double[] b = a; This copies a reference to the array, which means that a and b are now aliased. To build a new array, we have to use new to allocate space, and a loop to copy the elements of the array. double[] b = new double [3]; int i = 0; while (i < 4) { b[i] = a[i]; i++; }