CPSC 124, Spring 2021:
Sample Answers to the Second Test

Question 1. Java has global variables and local variables. What, briefly, is the basic difference between them?

Answer. Local variables are declared inside subroutine definitions (and can only be used in the subroutine in which they are declared). Global variables are declared outside any subroutine definition.

Question 2. Discuss what is meant by a constructor (in the context of this course). Include a specific example of using a constructor.

Answer. A constructor is a special kind of subroutine in a class, whose purpose is to create and initialize new instances of that class. A constructor can be recognized by the fact that it has no return type, and its name is the same as the name of the class. Constructors are called using the new operator. An example would be the constructor [public Point(int a, int b)] in the Point class in problem 6 on this test.

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

a)public
b)private
c)final
d)static

Answer.

a) public means that the subroutine or variable can be used from any class.

b) private means that the subroutine or variable can on be used in the class where it is declared.

c) When applied to a variable, final means that the value stored in the variable cannot be changed after the variable is initialized.

d) A static variable or subroutine is part of the class itself. There is only one copy, and it exists as long as the class exists. The non-static part of the class, on the other hand, only serves as a template for making instances of that class. When an instance of the class is created, it gets its own copies of any non-static variables and subroutines from the class

Question 4. Consider the following subroutine definition:

public static String guess(String str) {   
    String result = "";   
    for (int i = 0; i < str.length(); i++) {   
       if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {   
          result = result + str.charAt(i);   
       }   
    }   
    return result;   
}

a) What is the return type of this subroutine?

b) What is the value of guess("John Q. Doe")?

c) What is the purpose of this subroutine? What does it do, in general, for any given input? Explain your answer.

d) What happens if guess(null) is called? Why, exactly?

Answer.

a) String

b) "JQD"

c) The subroutine returns a string that contains all of the upper case letters from the parameter string that is passed to the subroutine. The code in the subroutine starts with an empty string. Then it goes through the parameter, str, character by character. (The expression str.charAt(i) represents the i-th character from str.) If the character is an uppercase letter, that is, in the range 'A' to 'Z', then it is added to the end of the result string. At the end, the result string is returned as the value of the subroutine.

d) A NullPointerException will be thrown, when an attempt is made to evaluate str.length(). This happens because if str is null, then there is no actual string and str.length does not exist.

Question 5. A common task is to read an integer from the user (using TextIO) that is within a given range of values, from some specified minimum to some specified maximum. Write a subroutine that does this. The minimum and maximum integer values are parameters, and the return value is the input number from the user. Use a while loop to ensure that the number is valid.

Answer.

public static int( int min, int max ) {
    int n;
    while (true) {
        System.out.printf("Enter an integer in the range %d to %d: ", min, max);
        n = TextIO.getln(int);
        if (n >= min && n <= max)
           break;
        else
           System.out.println("Please enter a number in the specified range!");
    }
    return n;
}

Question 6. Consider the class Point defined below. Write a Java code segment that will produce the picture at the right when it is executed. That is, declare three variables named pt1, pt2, and pt3. Then create some objects, with the end result as shown in the picture.

public class Point {
    public int x, y;
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}

Answer.

Point pt1, pt2, pt3;
pt1 = new Point(5,18);
pt2 = new Point(32,7);
pt3 = pt2;

Question 7. Write a definition for a static subroutine that satisfies the following description: The name of the subroutine is almostEqual. It has two parameters of type double, and it returns a boolean value. The return value is true if the absolute value of the difference between the parameters is less than 0.000005 and otherwise is false. (Absolute value can be computed with the function Math.abs.)

Answer.

public static boolean almostEqual( double x, double y ) {
    if ( Math.abs(x-y) < 0.000005 )
        return true;
    else
        return false;
}

Question 8. For a word processing program, a subroutine is needed that will print out a line of asterisks, such as ****************. The number of asterisks is to be given as a parameter to the subroutine. Write a subroutine named lineOfStars that will print a specified number of asterisks, on the same line, followed by a carriage return.

Answer.

public static void lineOfStars(int starCount) {
   for (int i = 0; i < starCount; i++) {
       System.out.print("*");
   }
   System.out.println();
}

Question 9. Write a static subroutine named fill with two parameters, where one parameter is an array of int, and the other is a simple int value. The subroutine should fill the entire array with copies of the second parameter. There is no return value.

Answer.

public static void fill(int[] A, int val) {
   for (int i = 0; i < A.length; i++) {
       A[i] = val;
   }
}

Question 10. Give two different reasons for using named constants (that is, final static global variables).

Answer.  (1) A name such as INTEREST_RATE is more meaningful than a literal number such as 0.035, so using named constants can make the program easier to understand.  (2) If the name is used consistently, it will be easy to change the value of the named constant, since the value only has to be changed where the named constant is declared, not every place in the program were it is used.  (3) The value of the named constant is protected from being changed accidentally (but this is really not an interesting reason!).

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

Answer. "Black boxes" are an essential tool for handling complexity. A black box has an interface and an implementation. The interface makes it possible to use the black box without understanding its implementation. Furthermore, the creator of the black box can design the implementation without knowing all the details of how the black box will be used, and the implementation can be changed if necessary, as long as the interface and function is not changed, without changing all the systems that use the black box.

When considering a subroutine as a black box, the interface includes the name, parameter list, and return type. It is possible to use the subroutine correctly as long as you know its interface. The implementation is the code inside the subroutine definition. Users of the subroutine don't have to understand the code, and the writer of the subroutine doesn't need to know all the possible ways that the subroutine will be used. [This is only describing the syntactic part of the interface, which makes it possible to write legal calls to the subroutine. The interface also has a semantic component that you need to understand in order to use the subroutine effectively. The semantic component is usually described in the Javadoc comment for the subroutine.)

When considering a class as a black box, the interface includes non-private global variables and the interfaces of all non-private subroutines. These are the only parts that are visible from outside of the class. The implementation is everything else — the private global variables and subroutines as well as the code inside all of the non-private subroutines.