CPSC 124, Fall 2005
Answers to Quiz #6

Question 1: What does it mean to sort an array?

Answer: To sort an array means to put its elements in order, either ascending or descending. (Of course, this only makes sense if some sort of ordering in defined for the possible element values. For example, arrays that hold numbers can be sorted into numerical order and arrays that hold strings could be sorted into alphabetical order.)

Question 2: Write Java code that will create a two-dimensional array of int with 3 rows and 4 columns, and will store a 17 into each element of the array.


            int[][]  array2D;         // Declare the array variable.

            array2D = new int[3][4];  // Create the array object.

            for (int row = 0; row < 3; row++) {   // Fill the array with 17's.
                for (int col = 0; col < 4; col++)
                    array2D[row][col] = 17;

Question 3: What is polymorphism?

Answer: When an instance method is called in Java, the meaning can generally be determined only at run time, because the meaning can depend on the actual type of object involved. This is called polymorphism. Polymorphism occurs because a variable, t, of type T can refer to an object belonging to class T or to any subclass of T. The meaning of t.doMethod() can depend on the type of the object to which t refers at the time this method is executed, because different versions of the method doMethod() can be defined in different subclasses of T.

Question 4: What is an abstract class, and why do abstract classes exist?

Answer: An abstract class is one that cannot be used for creating objects, but can still be used for creating subclasses. An abstract class exists to express the common properties of its subclasses. A variable whose type is given by an abstract class can refer to an object belonging to any of the concrete subclasses of the abstract class.

Part 2: Suppose that a two-dimensional array

             double[][]  highTemps  =  new int[100][366];

has already been filled with data about high temperatures in each of 100 different cities on each day of 2004. The array element highTemps[c][d] represents the high temperature in city number c on day number d.

Write Java code that will print out the average high temperature for each city. (For each city, add up all the high temperatures for that city and divide by the number of days in the year.)


            for (int city = 0; city < 100; city++) {
                double sum = 0;  // Sum of all the high temperatures for this city.
                for (int day = 0; day < 366; day++)
                    sum = sum + highTemp[city][day];
                double average = sum / 366;  // Average high for this city.
                System.out.println("The average high for city " + city + " was " + average) + ".");

David Eck, 7 December 2005