CPSC 124, Fall 2011
Quiz #5
Question 1. Explain the meaning of the Java directive
import java.awt.Color;
What is "java.awt"? What is the effect of the directive?
Answer. java.awt is a package. A package is a collection of related classes (and possibly subpackages). Java comes with many standard packages; java.awt is one of them. It contains basic classes related to GUI programming.
Color is one of the classes in the package java.awt. The statement "import java.awt.Color" at the top of a source code makes it possible to refer to the class as "Color" instead of "java.awt.Color". Note that without the import statement, it is still possible to use the Color class. You just have to refer to it using its full name, java.awt.Color.
Question 2. State two important reasons to use symbolic constants (which are created using the final modifier).
Answer. (a) Names are more meaningful than numbers or other literals, so using symbolic constants can make a program easier to read and understand.
(b) If a constant value is given as a symbolic constant, then, if the value ever needs to be changed, it will only have to be changed on one line in the program, where the symbolic constant is defined. If you used literal constants instead, and you wanted to change the value, you would have to track down every point in the program where the literal constant is used, and make the change at each such point.
Question 3. Write a subroutine named contains with a parameter str of type String and a parameter ch of type char. The return type of the subroutine is boolean. The return value is true if ch occurs as one of the characters in str; if not, the return value is false. Use a loop to look through the string for ch.
Answer.
public static boolean contains(String str, char ch) { for ( int i = 0; i < str.length(); i++ ) { if ( str.charAt(i) == ch ) return true; } return false; }
(Except for the "public", the first line of the answer is pretty much determined by the description given in the problem. The function returns true/false values, so the return type must be boolean. The name of the function is contains, and the names and types of the parameters are specified. In the definition of the function, you have to look through all the individual characters in the string, and see whether any of them is equal to ch. As soon as you find a character that satisfies this, you know that the answer is true, and you can immediately return that value. You cannot, however, return false until after you have checked every character. This means that the return false has to come after the for loop, not inside the loop.)