CPSC 124, Winter 1998

Second Test

This is the second test given in CPSC 124: Introductory Programming, Winter 1998. See the information page for that course for more information.

The answers given here are sample answers that would receive full credit. However, they are not necessarily the only correct answers.

Question 1: What is a constructor? What is the purpose of a constructor in a class?

Answer: (Quoted from the solutions to Quiz 4.) A constructor is a special kind of subroutine in a class that has the same name as the name of the class and that has no return type, not even void. A constructor is called with the new operator when an object is created. Its main purpose is to initialize the newly created object, but in fact, it can do anything that the programmer wants it to do.

Question 2: Explain carefully everything that the computer does when it executes the declaration statement:

Color hue = new Color(180,180,255);

Answer: In this statement, a new object is created and is assigned to a newly created variable. To do this, the computer performs the following four steps:

  1. Space is allocated on the heap to hold an object belonging to the class Color.
  2. A constructor from the Color class is called to initialize the object, and the parameters 180, 180, 255 are passed to this constructor.
  3. Space is allocated for a new variable named "hue"".
  4. A pointer to the new object is stored in the variable hue.

Question 3: Some of the applets that you have worked with in lab use an off-screen Image to do double buffering. Explain this. (What are off-screen Images? How are they used? Why are they important? What does this have to do with animation?)

Answer: An off-screen Image is a segment of the computer's memory that can be used as a drawing surface. What is drawn to the off-screen Image is not visible on the screen, but the Image can be quickly copied onto the screen with a drawImage() command. It is important to use an off-screen Image in a situation where the process of drawing the image should not be seen by the user. This is true, for example, in animation. Each frame of the animation can be composed in an off-screen Image and then copied to the screen when it is complete. The alternative would be to erase the screen and draw the next frame directly on the screen. This causes unacceptable flickering of the image.

Question 4: Variables in a class can be either instance variables or static variables. When you declare a variable, you have to decide whether to make it static or instance. Explain how you can decide, and give several examples.

Answer: When a class declares an instance variable, every object of that class gets its own copy of the instance variable. This means that the variable can have different values in different objects. For example, in a Rectangle class, where an object represents a rectangle drawn on the screen, instance variables could be used to store the position, size, and color of the rectangle. Then every Rectangle would have its own position, size, and color. Suppose that the color were stored in a static variable instead of in an instance variable. A static variable belongs to the class rather than to the object created with that class. This means that there would be only one color that applies to all Rectangle objects. Changing the value of that static variable would, presumably, change the color of every Rectangle that exists!

On the other hand, there are some cases where static variables are appropriate. For one thing, static methods can only use static variables, not instance variables. Static variables can also be used to store data that pertains to the whole class. For example, suppose you want to keep track of the number of Rectangle objects that exist. This value can be stored in a static variable in the Rectangle class. It wouldn't make sense to use an instance variable since there is only one value, not one value per object.

Question 5: a) In your second programming assignment, you worked with roman numbers. Suppose that you wanted to represent roman numbers as objects. How would you design a class, RomanNumber, so that each object belonging to the class represents a roman number? List the instance variables, methods, and constructors that you would include in the class, and state what each one is for. For the methods and constructors, specify the parameters and return type as well as the name; however, do not give full definitions. (The class you describe must work with part b) of this problem.)

b) Assume that the RomanNumber class from part a) is already written. Write a complete main program, using that class, that will read two roman numbers from the user, add them, and print the result. The class you described in part a) must include any methods that you need to write this program.

Answer: (A Roman number has a value. The class needs an instance variable to represent that value. It is convenient to be able to construct Roman numbers from strings or from ints. Instance methods provide for the conversions in the opposite direction: from Roman number to int and from Roman number to String. This gives a pretty minimal class, but it's sufficient for writing the program in part b.)

     a)   class RomanNumber {

             int value;  // The int with the same numerical value as 
                         // this roman number.  (Could use a String
                         // representation instead, but this is easier.)

             RomanNumber(String rn) { ... }
                 // Assume rn is a string such as "MCXII" that represents
                 // a roman number.  Construct that roman number.

             RomanNumber(int N) { ... }
                 // Construct a roman number with value N.

             int getIntValue() { ... }
                 // Return the int with the same value as this roman number.

             String toString() { ... }
                 // Return a string representation of this Roman number.


     b)   public class AddRoman {
             public static void main(String[] args) {
                Console console = new Console();
                console.put( "Enter a Roman number: " );
                RomanNumber rn1 = new RomanNumber( console.getln() );
                console.put( "Enter another Roman number: " );
                RomanNumber rn2 = new RomanNumber( console.getln() );
                int sum = rn1.getIntValue() + rn2.getIntValue();
                RomanNumber sum = new RomanNumber( sum );
                console.putln( "The sum is: " + sum.toString() );

Question 6: Describe the picture that is produced by the following paint method.

               public void paint(Graphics g) {
                  int redLevel = 0;
                  for (int x = 0; x < 256; x++) {
                     g.setColor( new Color(redLevel, 0, 0) );
                     g.drawLine( x, 0, x, 255 );

Answer: Here is what the image looks like (except that you need a full-color monitor to display it properly):

Black-to-red Gradient

This image is a square made up of 256 vertical lines. Each line is 256 pixels long. Each line is a different color. Moving from left to right, the amount of red in the color increases. At the left, the lines are pure black; at the right, the lines are pure red. (There is no green or blue in any of the colors.)

Question 7: Write a subroutine that finds the sum of all the numbers in an array of int's. The subroutine should be named arraySum. It should have one parameter of type int[], and it should return a value of type int. The value that is returned should be obtained by adding up all the numbers in the array.


         static int arraySum(int[] A) {
               // Returns the sum of the numbers in A.
            int sum = 0;
            for (int i = 0; i < A.length; i++)
               sum += A[i];
            return sum;

Question 8: Suppose that a class, Employee, is defined as follows:

                class Employee {
                   String lastName;
                   String firstName;
                   double hourlyWage;
                   int yearsWithCompany;

Suppose that data about 100 employees is already stored in an array:

                Employee[] employeeData = new Employee[100];

Write a code segment that will output the first name, last name, and hourly wage of each employee who has been with the company for more than 20 years. (Assume that there is a console variable to use for output.)

Answer: (The data for the i-th employee is stored in an object that can be referred to as employeeData[i]. The four pieces of data about that employee are members of this object and can be referred to as:

The code segment uses a for loop to consider each employee in the array.)

        for (int i=0; i < 100; i++) {
            if ( employeeData[i].yearsWithCompany > 20 )
                console.putln(employeeData[i].firstName + " " +
                              employeeData[i].lastName + ": " +

Question 9: Java uses garbage collection. What is meant here by garbage collection?

Answer: When an object on the heap is no longer pointed to by any variable, then that object can play no further role in the program. It is "garbage." Java keeps track of references to objects, so that it can recognize when they are no longer in use. When that happens, they can be garbage collected, and the memory that they occupy can be reused.

Question 10: A checkers board is an 8-by-8 grid of squares that contains empty spaces, red pieces, and black pieces. (For this problem, ignore the possibility of "kings.") Assume that the contents of a checkers board are stored in an array

                    int[][] board = new int[8][8];

The value of board[row][col] represents the square in row number row and column number col. A value of 1 represents a red piece and a value of 2 represents a black piece. An empty square is represented by a value of zero.

Write a code segment that will determine whether the board contains more red pieces, more black pieces, or the same number of red pieces and black pieces. You can print out your answer on a console.


        int redCount = 0;   // number of red pieces
        int blackCount = 0; // number of black pieces

        for (int row = 0; row < 8; row++)
           for (int col = 0; col < 8; col++) {
              if (board[row][col] == 1)
              else if (board[row][col] == 2)

        if (redCount > blackCount)
            console.putln("There are more red pieces.");
        else if (redCount < blackCount)
            console.putln("There are more black pieces.");
            console.putln("The numbers of red and black pieces are equal.");

Question 11: The distinguishing features of object-oriented programming are inheritance and polymorphism. Write an essay discussing these two terms. Explain what they mean and how they are related. Discuss how they can be useful in designing and writing programs. Include some examples in your answer.

Answer: inheritance allows a programmer to reuse and build on previous work. A new class can be created that "extends" an existing class. The new class inherits all the variables and methods of the existing class and can then add to and modify the stuff that it inherits. So the work that was done creating the original class does not have to be redone. (In fact, the original code does not have to be modified -- which can be a difficult and error-prone task. The original class remains unchanged. The changes are all isolated in the new class.)

Polymorphism can arise whenever one or more classes inherit from a base class. If some method in the base class is overridden in a subclass, then that method is "polymorphic." If doSomething() is a polymorphic method, then the result of calling anObject.doSomething() will depend on the actual class of the object anObject. For example, suppose that a Vehicle class has subclasses named Car, Train, and Boat. Suppose that go() is a polymorphic method that is defined in Vehicle and overridden in the subclasses. If myVehicle is a variable of type Vehicle, then myVehicle can refer to an object belonging to any of the classes Vehicle, Car, Train, and Boat. The method called by "myVehicle.go()" is the one that is appropriate to the object that myVehicle points to.

In addition to making reuse of existing work easier, polymorphism and inheritance can be useful when a program is being designed. Suppose that several classes have been identified and that it is recognized that those classes have certain properties or behaviors in common. In that case, the common properties and behaviors can be encoded in a common base class, so that they only have to be written once. Polymorphism allows each subclass to display somewhat different versions of common behaviors.

David Eck 2 March 1998