CS 124, Fall 2009
Solutions to Quiz #4

1. What is the meaning of the modifiers public and private?

Answer: These modifiers can be applied to the definitions of subroutines and member variables. A subroutine or variable that is declared as "private" can be used in the class in which it is declared; from outside that class, it is invisible. A subroutine or variable that is declared as "public" can be accessed from anywhere.

2. As the term is used in Java programming, what are packages and why do they exist?

Answer: A package is just a collection of classes (and other packages), similar to a directory in a file system. A class can be declared to be in a package, and then the full name of the class includes the name of the package. Packages can be used to organize related classes and to avoid naming conflicts, since two classes can have the same name as long as they belong to different packages.

3. "A subroutine can be used as a black box." What does this mean and why is it important?

Answer: Something can be used as a black box without understanding how it is implemented. The implementation is the code inside the subroutine, and you don't have to understand that code in order to use the subroutine. You just have to know what task it performs. This means that once a subroutine has been written, you don't have to think about how it works. The design of the subroutine is separated from the design of the programs that use it, reducing the complexity of both designs.

4. Write a complete Java subroutine named countChars that has one parameter of type String and one parameter of type char. The subroutine should count the number of times that the given character occurs in the given string. The answer should be returned as the value of the subroutine. For example, countChars("xxyyyzzzz",'y') should return the value 3.

Answer:

      public static int countChars( String str, char ch ) {
         int count;  // The number of times ch has been found in str.
         int i;      // Position in the string str.
         count = 0;
         for ( i = 0; i < str.length(); i++ ) {
           if (str.charAt(i) == ch)
             count++;  // We've found an occurrence of ch add 1 to count.
         }
         return count;
      }