Sample Final Name:____________________________________
CS 3230
Instructor: Delroy Brinkerhoff Score:________________
INSTRUCTIONS: Covers vol 1: chaps 9, 10, 14; vol 2: 1, 3, 6 (tables and trees); and the Stratego project
1. Consider the following fragments of code and choose the most accurate, relevant, and complete description. (Note that the line numbers are not a part of the code.)
1: public class Foo implements ActionListener, MouseListener { }
2:
3: public class Bar
4: { private Foo f = new Foo();
5: private JButton button = new JButton(“Open”);
6: private JPanel panel = new JPanel();
7:
8: button.addActionListener(f);
9: panel.addMouseListener(f);
10: }
a. There will be a compile error on line 9 because panels may not be a mouse event source.
b. There will be a compile error on line 9 as the Foo object f is already listening to button.
c. The code will compile and run but the Foo object f will only respond to panel because it registered last and overwrote button.
d. It will compile and run without error because is it possible for Foo object f to be a listener to both the button and the panel at the same time.
ans: d Feedback:
General: In general, a listener object can listen to multiple event sources and a single event source can send its event to multiple listeners (i.e., the connection between event sources and listeners can be a many-to-many relation).
2. It possible to call the methods of a Thread while the Thread is in the new state.
a. True b. False ans: a
Feedback:
General: A thread is an object, which implies that its methods can be called at any time.
3. It possible to call the methods of a Thread while the Thread is in the dead state.
a. True b. False ans: a
Feedback:
General: A thread is an object, which implies that its methods can be called at any time.
4. The Producer/Consumer problem requires objects instantiated from (minimally) three classes; which object(s) must run as concurrent threads?
a. Buffer b. Consumer c. Producer
d. Buffer and Consumer e. Buffer and Producer f. Consumer and Producer
g. Buffer, Consumer, and Producer ans: f
Feedback:
General: The Producer and Consumer are threads while the buffer is passive (i.e., it is not active but only responds to requests from Producers and Consumers). The Buffer is an example of a monitor: a class with one or more synchronized methods (Insert and Remove). The mutual exclusion algorithm illustrated in this problem requires that each synchronized method begin with a call to wait (enclosed in an if- or while-statement) and end with a call to notify or
notifyAll. Although the wait/notifyAll pair is defined in the synchronized Buffer methods, it is actually the Producer and Consumer threads that call these methods.
5. What does the following code print?
class TestThread extends Thread {
public void run() {
System.out.println("Running");
}
public static void main(String[] args) { TestThread tt = new TestThread();
tt.run();
} }
a. prints Running
b. prints Running Running on separate lines c. The program does not produce any output
d. Causes a run time exception (you cannot call a thread’s run method directly) ans: a
Feedback:
General: It is legal to call the run method directly but this does not involve multi-threading or concurrent execution.
6. What does the following code print?
class TestThread extends Thread { private int count = 0;
public void run() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) { TestThread tt = new TestThread();
tt.start();
System.out.println(getCount());
} }
a. prints either 0 or 1, but it is not possible to predict which is printed b. print 0
c. prints 1
d. The program does not produce any output ans: a
Feedback:
General: The start method begins a new thread running, which in this example runs concurrently with the main thread. It is a thread’s run method that is executed concurrently. Once threads are running, it is not possible to tell the order in which they will execute.
7. An instance of the java.io.File class can represent a file or a directory.
a. True b. False ans: a
Feedback:
General: File objects represent “things” in the file system, including directories (or folders). File objects carry out many of the tasks required to manage a file system - everything except reading or writing files.
8. A Java IO class whose name contains “Stream” reads or writes what kind of data?
a. Numeric b. Text c. Neither ans: a
Feedback:
General: Stream classes read and write streams of bytes, which are numeric data. Classes with Reader or Writer in the name deal with textual data.
9. The following statements appear in a class that extends JFrame and uses the default layout manager.
setSize(300, 300);
JButton red = new JButton(“Red”);
add(red);
JButton blue = new JButton(“Blue”);
add(blue);
setVisible(true);
Briefly describe the frame’s appearance.
ans: essay feedback:
general: It will display a typical window 300 pixels wide and 300 pixels high using with the Java or metal look and feel, and with one button labeled “Blue” filling the frame.
10. Following are four methods commonly used to implement a graphical user interface (GUI).
Which method deactivates and grays out a component?
a. revalidate b. repaint c. setEnabled d. setVisible ans: c
feedback:
general: You should be familiar with all four methods. Several classes define a setVisible method that, at a high level, describe the same behavior. However, the Window version also starts a thread (the event dispatch thread) that makes the window displayable.
11. Which statement best describes the behavior of the revalidate method?
a. Schedules a repaint event, which causes the paintComponent to be called with a properly configured Graphics object.
b. Forces a layout of a component after the contents or configuration fo the component have changed.
c. Allows or disallows a component to respond to user input and to generate events.
d. Shows or hides a component; the Window version also makes the window displayable.
ans: b feedback:
general: Call repaint whenever you need to update the display with paintComponent; call revalidate update the display in any other way. Some cases require calling both.
12. The TokenHandler class determines the result of one token striking another with the following statement:
result = token.strike(opponentToken);
Choose the best statement
a. The strike method is fully implemented as attacked.rank - this.rank.
b. The strike method is fully implemented as this.rank - attacked.rank.
c. Calls the strike method defined in class Token to determine which token wins.
d. Polymorphically calls the strike method defined by the token object to determine which token wins.
ans: d feedback:
general: The strike method returns a positive value (token wins), 0 (a tie), or a negative value (opponentToken wins). Generally, tokens with a lower rank defeat tokens with a higher rank;
therefore, a is correct except when dealing with bombs or the flag. The Token strike method implements this general behavior and test for the special cases of the opponentToken being a flag or a bomb. Two classes override the strike method, which is polymorphically called when a miner strikes a bomb or when a spy strikes a marshal.
13. Which of the following is NOT true of the singleton design pattern?
a. Requires that the single instance be created in main.
b. Ensures that a program has exactly one instance of a class.
c. Provides a global point of access the one instance of a class in a program.
d. Limits the number of instances by restricting access to the constructor.
ans: a feedback:
general: It was convenient in the stratego program to create the single instance of Stratego in main. However, the single instance is more typically created in either the getInstance method or in an initialization method.
14. Creating an executable jar file requires a manifest containing which of the following statements? (Note that 5 denotes pressing the enter key.)
a. Main-Class: Stratego b. Main-Class: Stratego5 c. Manifest-Version: 10 d. Sealed: true
ans: b feedback:
general: c represents the contents of a minimal jar file (and although an executable jar file does not require the entry, it is a good idea to include it). d seals a jar file using encryption so that it is not possible to add new classes to the jar. Sadly, if you create a manifest like a, it will not work and it generally does not produce any error diagnostics.
15. The Single-Thread Rule states: “Do not touch Swing components in any thread other than the event dispatch thread.” Which of the following related design rules has changed beginning with Java 1.6?
a. If an action triggered by swing event takes a long time, start a new thread to do the work.
b. If an method can block on input or output, start a new thread to do the work.
c. If you need to wait for a specific amount of time, start a new thread to sleep.
d. You can safely add or remove event listeners in any thread.
e. You can construct components, set their properties, and add them to containers as long as none of the components have been realized.
ans: e feedback:
general: Rules a-c are intended to keep the interface responsive - if the event dispatch thread is busy with any of these tasks, it cannot respond to user input. Adding or removing listeners is fast and safe. You should use one of two EventQueue methods (invokeAndWait or invokeLater) to manipulate any swing component from any thread other than the event dispatch thread. Prior to Java 1.6 it was acceptable to construct a display with the main thread, and the single-thread rule was only enforced after the display was realized (i.e., made displayable). Most of the examples presented in class and posted on the class website follow this older rule. Beginning with Java 1.6, the single-thread rule requires (although it is not enforced by the compiler) that you use the EventQueue methods in main to construct the GUI.
16. Java defines two methods to restart waiting threads: notify and notifyAll. Using the bounded buffer problem as an example, briefly describe why the notifyAll method is safer and therefore preferred.
ans: essay
17. The wait method allows a thread to voluntarily suspend itself if a monitor is not in a state useable by the thread. The thread may test the state either in an if-statement or a loop.
Explain briefly why the preferred Java style is to use a loop.
ans: essay
18. The wait, notify, and notifyAll methods may only be called from within a synchronized method. Briefly explain how this restriction enforces the concept of an “atomic test and set” when coupled with the if-statement or loop mentioned in the previous question.
ans: essay
19. Briefly describe the sequence of events that take place when the ServerSocket accept method is called and then detects a connection.
ans: essay
20. Briefly describe, in terms of the necessary layout manager(s), how to place the playing field and two trays of tokens in the Stratego frame.
ans: essay