CPSC 124, Fall 2017: Sample Answers to Test #2

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. Subroutine and global variable declarations can include the modifiers public, private, and static. Briefly explain what each of these modifiers means.

a)  public

b)  private

c)  static


a)  A public variable can be used in any class in the program. However, outside the class where it is defined, it is referred to using a full name containing the name of the class where the variable is declared (if it is static) or the name of an object belonging to that class (if it is not static), as well as the name of the variable itself.

b)  A private variable can only be used in the class where it is declared.

c)  A static variable is a property of the class itself. There is only one copy of the variable, and it exists as long as the program is running.

Question 2. A "named constant" is a final static variable. Give two different reasons for using named constants in a program (instead of just using the literal values).

Answer. One reason is that using a named constant gives a meaningful name to a quantity, which helps to make the program easier to read and understand. Another reason is that if the value of the constant needs to be changed (which can only be done by re-compiling the program), the value only needs to be changed in the one place in the program where the named constant is declared; on the other hand, if the literal value were used in several places throughout the program, you would have to hunt down every occurrence and change it.

Question 3. What is meant by a constructor in a class? Explain how and why constructors are used? (How is a constructor called?)

Answer. A constructor is a special kind of subroutine that is called using the new operator. The new operator is used to create new objects. When this is done, a constructor is called, and the usual job of the constructor is to initialize the object by assigning initial values to instance variables in the object. For example, the expression  new Color(200,100,50)  creates a new object of type Color and calls a constructor in the Color class to initialize that object. In this case, the constructor assigns values to the red, green, and blue components of the color. A constructor definition can be recognized by the fact that the name of the constructor is that same as the name of the class, and it has no return type (not even void).

Question 4. Write a static void subroutine that takes one String as its parameter. The subroutine should print that string 25 times.


public static void print25( String str ) {  // (any name is OK)
    for (int i = 0; i < 25; i++) {
        System.out.println( str );

Question 5. Write a static subroutine named countChar with one parameter of type String and one parameter of type char. The return type is int. The subroutine counts the number of times that the char occurs in the String, and it returns the answer.


public static int countChar( String str, char ch ) {
    int count = 0;
    for ( int i = 0; i < str.length(); i++ ) {
        if ( str.charAt(i) == ch ) {
            count = count + 1;
    return count;

Question 6. Write a static subroutine named allPositive with one parameter of type int[] (array of int). The return type is boolean. The return value from the subroutine should be true if every element of the array is greater than zero; it should be false if there is at least one element that is less than or equal to zero.


public static boolean allPositive( int[] array ) {
    for ( int i = 0; i < array.length; i++ ) {
        if ( array[i] < 0 ) {
            return false;  // (the array has a negative element)
    return true;  // (all the elements were >= 0)

Question 7.  a) Write a complete definition for a simple class named Player (representing a player in some game). The class must have instance variables to represent the name and the score of the player. It must have a constructor that specifies the name of the player. It must have an instance method that adds some points to the player's score (with a parameter to tell how many points to add). And it must have getter methods that can be used to get the name and to get the current score.

b)  Using your class from part (a), write a few lines of code that will create an object of type Player with name "Fred", and give that player 42 points.



     public class Player {

         private String name;
         private int score;    // (initial value is automatically zero)
         public Player( String playerName ) {  // (the constructor)
             name = playername;
         public void addPoints( int points ) {  // (add points to the score)
             score = score + points;
         public String getName() {  // (getter method for the name)
             return name;
         public int getScore() {  // (getter method for the score)
             return score;


     Player player;
     player = new Player("Fred");

Question 8. What is meant by a package in Java?

Answer. A package groups a collection of related classes together so tha they can thought of as a unit. For example, the package java.awt contains the basic classes needed for GUI programming. (A package can also contain subpackages.)

Question 9. What is the heap?

Answer. The heap is the region in the computer's memory where objects are stored. The new operator allocates memory in the heap for the newly created object.

Question 10. A subroutine is a black box, but it can interact with the rest of the program through parameters, return values, and global variables. Explain these terms and explain how parameters, return values, and global variables are used for communication between subroutine and program.

Answer. A black box is something that has an interface and an implementation, and it interacts with the outside of the box only through its interface. A subroutine is a kind of black box, where the implementation is the code that is inside the definition of the subroutine. The interface of the subroutine consists of the parameters and the return value of the subroutine and, less obviously, any use of global variables in the definition of the subroutine.

Parameters are inputs to the subroutine. The values of parameters come from outside the subroutine, when the subroutine is called from elsewhere in the program. For example, in the subroutine call System.out.println("Fred"), the parameter value is "Fred", and it tells the subroutine that "Fred" is the string that it should print.

A subroutine can return a value. A return value is an output from the subroutine. Its value is created inside the subroutine, and is sent back to the point in the program where the subroutine was called. For example, in the statement x = Math.sqrt(2), the sqrt subroutine computes the value of the square root of 2, and that value is returned so that it can be assigned to x.

But subroutines can also interact with rest of the program through global variables. A global variable is a variable that is declared outside any subroutine, so that it can be used in more than one subroutine. When a subroutine accesses a global variable, it is using a value from outside itself, and when it sets the value of a global variable, that value can also be seen by other subroutines. (This is communication between the inside of the subroutine and the outside, but it is sort of sneaky.)