CPSC 124, Spring 2013
Sample Answers to the Second Test

Question 1. The following "modifiers" can be applied to the declarations of member variables and subroutines. Explain what each one means. (The last one requires a longer explanation!)

a) private

b) protected

c) final

d) static

Answer.

a) private means that the subroutine or variable to which it is applied can be accessed only in the same class where it is defined.

b) protected means that the method or variable to which it is applied can be accessed in the class where it is defined, in subclasses of that class, and in classes that are in the same package.

c) final says that the value of a variable to which it is applied cannot be changed after the variable has been initialized. It can be used to create named constants.

d) Subroutines and member variables can be either static or non-static. If something is declared as static, then it is actually an item in the class in which it is defined. It is created when the program starts and it exists as long as the program is running. There is only one copy of a static variable or subroutine. Non-static subroutines and member variables are also called instance methods and instance variables. They are not really part of the class. Instead they are there to serve as a template for objects that are created from the class. When an object is created with the new operator, the variables and methods that are in the object are specified by the instance variables and methods in the class. Each object gets its own copy, which is created when the object is created and destroyed when the object is destroyed.

Question 2. We say that subroutines and classes can be black boxes. Explain what this means and why it is important.

Answer. To say that subroutines and classes are black boxes means that they can be used without understanding the details of what goes on inside. To use a subroutine, you don't have to understand the "implementation," that is, the code inside the definition of the subroutine. You only need to know its "interface," meaning its name, parameter list, return type, and a description of the task that it performs. Similarly, you can use a class if you know its public interface, that is, its API.

Black boxes are an important tool for dealing with complexity. A black box can be a piece of a larger complex system, such as an entire program. It reduces the problems of building the whole system to smaller problems: build the individual black boxes, then put the boxes together. There are many advantages to doing things this way...

Question 3. Write a Java subroutine named max, with two parameters of type double, that returns the larger of its two parameters. For example, max(3.14,2.71) would return 3.14. (If the parameters are equal, it doesn't matter which one you return.)

Answer.

public static double max( double x, double y ) {
    if ( x > y ) {
        return x;
    }
    else {
        return y;
    }
}

Question 4. Write a subroutine that will strip extra spaces from a string. The parameter of the subroutine is a String. The return value is the same string, except that every substring of consecutive spaces has been replaced by a single space. For example, using ~ to represent a space, if the parameter is "Goodbye~~~cruel~~world", then the value returned by the subroutine is "Goodbye~cruel~world". (Hint: Copy a space from the input string to the output string only if the preceding character is not also a space.)

Answer.

public static String stripExtraSpace( String str ) {
    String stripped = "";
    for ( int i = 0; i < str.length(); i++ ) {
        if ( str.charAt(i) != ' ' || i > 0 || str.charAt(i-1) != ' ' ) {
            stripped = stripped + str.charAt(i);
        }
    }
}

Here is another version that you might find easier to understand:

public static String stripExtraSpace( String str ) {
   String stripped = "";
   for ( int i = 0; i < str.length(); i++ ) {
      char ch = str.charAt(i);
      if ( ch == ' ' ) { 
             // only some space characters are added to output
          if ( i == 0 ) { 
                 // this is the first character; has no preceding character 
              stripped = stripped + ' ';
          }
          else if ( str.charAt(i - 1) != ' ' ) {
                 // space is added only if preceding character is not a space
              stripped = stripped + ' ';
          }
      }
      else { // non-spaces just get added to output
          stripped = stripped + ch;
      }
   }
}

(The tricky part is that you have to be careful not to try to look at the "preceding character" if there is no preceding character. The first character has no preceding character.)

Question 5. Given the class Employee shown below, complete the subroutine printStaff so that it prints the name and salary of every item in the ArrayList.

public class Employee {    
   public String name;     
   public double salary;   
}                          

static void printStaff(ArrayList<Employee> staff) {
      .
      .  // fill in the definition!
      .
}

Answer.

static void printStaff(ArrayList<Employee> staff) {
   for (int i = 0; i < staff.size(); i++) {
       Employee emp = staff.get(i);
       System.out.println( "name: " + emp.name + 
            "; salary: " + emp.salary );
   }
}

Question 6. Consider the class Vec defined below. Write a Java code segment that will produce the following picture when it is executed. That is, declare three variables named v1, v2, and v3. Then create some objects, with the end result as shown in the picture.

public class Vec {
    public int x, y, z;
    public Vec(int a, int b, int c) {
        x = a;
        y = b;
        z = c;
    }
}

Answer.

Vec v1, v2, v3;
v1 = new Vec(3,4,5);
v2 = new Vec(7,2,8);
v3 = v2;

Question 7. For this problem, you should write a complete Java class definition. The name of the class should be RandMaker. An object of type RandMaker represents a source of random integers in the range from 1 up to some maximum value. The maximum value is an instance variable of the object. The class has a constructor that specifies the maximum value. It has a method named make that returns a random number. For example, the class could be used like this:

RandMaker rnd;  // A RandMaker to make numbers in the range 1..6
rnd = new RandMaker(6);
int d1 = rnd.make();  // get a random number
int d2 = rnd.make();  // get another random number

Write a class that meets these specifications and that could be used as shown.

Answer.

public class RandMaker {

   private int maxValue;
   
   public RandMaker( int max ) {
      maxValue = max;
   }
   
   public int make() {
      return 1 + (int)(max*Math.random());
   }

}

Question 8. What is null, in the context of this course?

Answer. Null is a pointer value that doesn't point to anything. It can be stored in a variable to mean that the variable does not refer to any object.

Question 9. To understand subroutines, you have to understand parameters. What are parameters, what are they for, and how are they used?

Answer. Parameters are used to provide information to a subroutine that it needs to perform its task. They represent input from somewhere else in the program, where the subroutine is called, into the subroutine. There are two kinds of parameters: The term "dummy parameter" or "formal parameter" refers to a parameter in the definition of the subroutine. Dummy parameters are just names. The term "actual parameter" refers to a parameter value that is provided in subroutine call statements. When a subroutine is called, the actual parameter values from the subroutine call are assigned to the dummy parameters in the subroutine definition before the subroutine is executed. For example, in problem 3 on this test, the 3.14 and 2.71 are actual parameters in the subroutine call max(3.14,2.17). When this is executed, the dummy parameters x and y are assigned 3.14 and 2.17 as their value before the code inside the subroutine is executed. Calling the subroutine with different actual values will produce a different result because the dummy parameters x and y will have different values.

Question 10. Two of the central concepts in object-oriented programming are subclasses and inheritance. Explain these terms and discuss why they are important.

Answer. It is possible for one class to "extend" another. For example:  public class B extends A. When this happens, B is said to be a subclass of A and A is the superclass of B. This means that B inherits everything that was already defined in A. That is, an object of type B contains all the instance variables and instance methods that are contained in an object of type A. B can add new variables and methods to those that it inherits. It can also override methods that are inherited from A; that is, it can change the definition of a method that it inherits. If we think of methods as "messages," this means that objects of type B and objects of type A can respond to the same message in different ways. (This is called polymorphism.)

Subclassing and inheritance are important for several reasons. They make code resusing easier: If you already have a class that does most of what you do, you can reuse that class by defining a subclass. You only have to program that parts that are different from the existing class. Furthermore, you can do this without modifying the original class in any way. This means that if you are confident that the original class is correct, then you only have to test the modifications that you make in the subclass. Because you don't have to change A, you can't accidentally break it!