CPSC 124, Spring 2014
Sample Answers to Quiz #4

Question 1. Suppose that the first line of a subroutine definition is

       public static void doSomething(String s, int n) {

a) What does "public" mean about the subroutine?

b) What does "void" mean about the subroutine?

c) Give an example of a subroutine call statement that calls this subroutine.

Answer.

a)  This method can be used anywhere in the program, including outside of the class where it is defined. Outside the class, it is referred to by its full name, including the class name.

b)  This subroutine does not return a value. It is not a function.

c)  doSomething("Hello", 17);

Question 2. What is meant by the implementation and by the interface of a black box?

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 3. a)  Write a function—that is a subroutine with a return value—that satisfies the following description: The name of the function is min. The function has two parameters of type double. The return type is also double. The value of the function will be the smaller of the two actual parameter values. (Note: If the two values are the same, it doesn't matter which one the function returns.)

b)  Give a very short Java code segment that uses your subroutine to print out the smaller of the two values 2.718 and 3.141. It can as short as be one line of code.

Answer.  (a)

    public static double min(double x, double y) {
        if (x < y) {
            return x;
        }
        else {
            return y;
        }

(The "public" could be left out or replaced by "private", since the question doesn't specify what access modifier to use. The "static" could also be left out, as far as the statement of the problem goes, but it makes more sense to have it there since this function has nothing to do with any objects. The names of the two dummy parameters don't have to be "x" and "y"; they can be anything. However, the return type, the name of the function, and the parameter types are specified in the problem and must be as shown.)

(b) System.out.println( min(2.718,3.141) );