CPSC 124, Spring 2006
Answers to Quiz #4


Question 1: What is meant by a "black box?"

Answer: A black box is something that can be used without understanding how it functions internally. A TV or a car is an example. In programming, a subroutine or a class can be considered to be a black box. Black boxes can be used as building boxes in more complex systems.


Question 2: In the Java programming language, what is a package, and why do packages exist.

Answer: A package is collection of classes and sub-packages. Packages exist in order to collect related classes into logical groups. Also, they are "namespaces" meaning that two classes can have the same name if they are in different packages; this allows developers to name their classes freely, without having to worry about what class names are being used by other developers.


Question 3: Suppose that the first line of a subroutine definition is static void process(int n, double x). Explain why process(17,20) is a legal call to this subroutine while process(42.5,8.33) is not.

Answer: The actual parameter that corresponds to a given formal parameter is legal if it could legally be assigned to the formal parameter. An int value can be assigned to a double variable, so the 20 in process(17,20) is OK. A double value cannot be legally assigned to an int variable, so the 42.5 in process(42.5,8.33) is not legal since the corresponding formal parameter, n, is of type int.


Question 4: In the declaration public final static int BASE_YEAR = 2004, what is the meaning of the word final?

Answer: The work "final" means that BASE_YEAR is a constant. That is, it is illegal to assign a new value to BASE_YEAR anywhere else in the program, so its value will always be equal to the initial value, 2004, that is assigned to it here.


Part 2: Write a complete subroutine named multiple that has one parameter of type String and one parameter of type int. It has a return type of String. The return value is a string consisting of multiple copies of the String parameter, where the number of copies is specified by the int parameter. For example, multiple("Rah!",3) returns the String

Answer: Note that the modifiers "public static" in the solution given here are not required by the description. The "static" modifier is optional and "public" could be replaced by "private" or could be left out entirely. This subroutine returns an empty string when repCount is less than or equal to zero. It is possible that negative values should be considered to be an error, but that's not required by the statement of the problem.

          public static String multiple(String str, int repCount) {

              String copies = "";
              
              for (int i = 0; i < repCount; i++) {
                  copies = copies + str;
              }
              
              return copies;
          
          }

David Eck, 8 March 2006