CPSC 124, Fall 2011
Quiz #4

Question 1. A black box has an interface and an implementation. Define interface and implementation.

Answer. The interface of a black box is how it interacts with the rest of the world. The implementation is what goes on inside the box. The idea is that to use a black box, it is only necessary to understand the interface. As a user, you don't need to understand the implementation.

Question 2. Write a static subroutine named max, with two parameters of type int and a return type of int. The subroutine should return the larger of its two parameters.

Answer. (The name of the subroutine has to be max, and the return type has to be int. There are two parameters of type int. The names of the parameters can be anything. My solution makes the subroutine public, under the assumption that it might be generally useful; however, that is not required.)

public static int max( int x, int y ) {
   if (x > y) {  // x is larger than y, so return x
      return x;
   }
   else {  // x is <= y, so return y.
      return y;
   }
}

Question 3. Write a subroutine with one parameter, str, of type String. The subroutine should print the characters of str in reverse order. For example, if str is "Hello World", then the output of the subroutine would be "dlroW olleH". Note that this subroutine does not return a value! It just outputs something to the screen.

Answer. (Since there is no return value, we want a void subroutine that outputs the reversed string using System.out.print. The algorithm is to go through the string from end to beginning, printing one character at a time. Another possibility would be to make a new string, containing the reverse of the original string, and output the new string all at once at the end. My solution is declared private, but public -- or no access modifier at all -- would also be acceptable.)

public static void printReversed( String str ) {
   var i; // loop control variable
   for ( i = str.length() - 1;  i >= 0;  i-- ) {
       System.out.print( str.charAt(i) );
   }
   System.out.println();
}