CSc 335 Test 2 Review Sheet followed by Practice Test

o  Tuesday 20 November 3:30-4:45 our usual lecture hall

o  Sit next to an aisle, against the wall, or have one empty seat to both your left and right

o  Worth 18% of your final grade

o  It is closed-book and closed-notes

Here is a preview of the questions Rick expects to have on the real test

1.  Analysis and Design: Given a problem specification: find the objects, write a sequence diagram that includes message names from the sender to the receiver (return types not needed)

2.  Match the Design Pattern name to the given Synopsis. Know short definitions of all design patterns we discussed: Iterator, Strategy, Observer, Command, Composite, Singleton, Factory, Decorator

3.  Write code, interfaces and/or classes for a problem using a Design Pattern that we have presented in class or section

4.  Write code, interfaces and/or classes for a problem using a Design Pattern not previously discussed in class or section.

5.  Networking question using Socket and SocketServer and their input and output streams.

6.  Drawing: Mostly knowing how to write code in paintComponent, calling repaint from the observers update method, and what a Timer does for animation. Know draw(Shape) where the classes implementing Shape are Rectangle2D.Double (x, y, w, h), Ellipse2D.Double(x, y, w, h), and Line2D.Double(x1, y1, x2, y2). An example of any required shape would be supplied, so there is no need to memorize shapes. We will also supply the paintComponent method heading and the cast to Graphics2D.

7.  Java Ranch questions

8.  Which is the better design Read these 28 refactorings from http://www.refactoring.com/

1.  Add Parameter
2.  Collapse Hierarchy
3.  Consolidate Conditional Expression
4.  Consolidate Duplicate Conditional Fragments
5.  Decompose Conditional
6.  Encapsulate Collection
7.  Encapsulate Field
8.  Extract Class
9.  Extract Method
10.  Extract Superclass
11.  Hide Method
12.  Inline Method
13.  Parameterize Method
14.  Pull up Field / 16.  Pull Up Method
17.  Remove Double Negative
18.  Replace Assignment with Initialization
19.  Replace Conditional with Polymorphism
20.  Replace Inheritance with Delegation
21.  Replace Iteration with Recursion
22.  Remove Control Flag
23.  Replace Error Code with Exception
24.  Replace Exception with Test
25.  Replace Magic Number with Symbolic Constant
26.  Replace Nested Conditional with Guard Clauses
27.  Replace Recursion with Iteration
28.  Reverse Conditional

C Sc 335 Practice Test 2 SL______Name ______150pts

1. Analyze and begin to design an information system for a video rental store.

§  Rents only videos, not computer games or other items.

§  A “video” can be in any medium: tape, DVD, and so on.

§  The store does not sell anything. For example, there are no sales of videos or food.

§  Cash-only payments

§  This is a real store with a real cashier register were transactions are carried out

§  On completion of a rental, the customer receives a transaction report with ‘typical’ information on it.

§  Each renter has a separate membership

1a) Create an initial list of candidate objects that would do a reasonable job of modeling this system. Also list their single responsibility

Candidate Object Name / Single Responsibility

1b) Write a sequence diagram to represent the objects relationships and messages involved in a scenario that begins when a valid customer arrives at the cashier with one video to rent (assume the store is open and the

Cashier is at a cash register).

2. Here are the names of all 23 Object-Oriented Design Patterns cataloged in the GoF book. Factory Method, Builder, Prototype, Singleton, Adaptor, Bridge, Composite, Decorator, Façade, Flyweight, Proxy, Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor. For each synopsis in the right column and write the matching design pattern name in the left column after each of the letters a. through k.

Pattern Name / Synopsis
a. / Provide a way to access the elements of a collection sequentially without revealing the underlying implementation.
b. / TBA
… / …
k. / TBA

3. The composite design pattern composes objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Here is the general form of the Composite Design Pattern:

In a real world example of composing a drawing (actually a bunch of instructions for a drawing), the following client code should generate the output shown:

Primitive p = new Primitive("Blue Line");

p.add(new Primitive("?Blue dot?"));

// Should print: 'Cannot add to a PrimitiveElement'

System.out.println();

// Create a tree structure to represent a composite drawing element

Composite root = new Composite("Picture");

root.add(new Primitive("Red Line"));

root.add(new Primitive("Blue Circle"));

root.add(new Primitive("Green Box"));

Composite comp = new Composite("Two Circles");

comp.add(new Primitive("Black Circle"));

comp.add(new Primitive("White Circle"));

root.add(comp);

// Add one more Primitive drawing element

Primitive yl = new Primitive("Yellow Line");

root.add(yl);

// Recursively display nodes

root.display();

Desired Output

'Cannot add to a PrimitiveElement'

draw Picture

draw Red Line

draw Blue Circle

draw Green Box

draw Two Circles

draw Black Circle

draw White Circle

draw Yellow Line

3a) Draw the UML Diagram to capture the real world example of Primitive and Composite drawing elements

o  List all class names using italics for abstract classes

o  Draw all relationships

o  Place the add methods in the correct places using italic when abstract

o  Place the display methods in the correct places using italic when abstract

3b) Using your UML diagram write the abstract class

3c) Using your UML diagram write the Primitive and Composite classes so your code represents the Composite as specified (need recursion in one method) and your output matches.

4. Write code, interfaces and/or classes for a problem using a Design Pattern not previously discussed in class or section. One of these: Adapter, Proxy, Mediator, State, or Chain of Responsibility.

Question not given for obvious reasons. It would look like the one above.

There may only be one Design Pattern Question on the test if Rick thinks it would be too much

5. Given that this code runs on a computer first:

ServerSocket serverSocket = new ServerSocket(4000);

System.out.println("This server now awaits one client");

Socket client = serverSocket.accept();

ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());

ObjectInputStream input = new ObjectInputStream(client.getInputStream());

String clientInput = (String) input.readObject();

System.out.println("Client wrote: " + clientInput);

output.writeObject("This server is shutting down.");
client.close();

and then the following code starts on the same computer

Socket server = new Socket("localhost", 4000);
ObjectOutputStream output = new ObjectOutputStream(server.getOutputStream());

ObjectInputStream input = new ObjectInputStream(server.getInputStream());

output.writeObject("I am a client");

String responseToMyOutput = (String) input.readObject();

System.out.println("Server wrote: " + responseToMyOutput);

server.close();

5a) What output does the server code generate? 5b) What output does the client code generate?

6. In the game of hangman, you are to guess a word by selecting letters. One part of the game is to have an image appears like this when the game begins:

For each wrong guess, another line is drawn on the hangman illustration. You lose if the drawing is finished before you've worked out the word. Using the code provided below (and a start to HangmanPanel), modify HangmanPanel to do whatever you have to do to draw the correct number of pieces of the hangman in the order shown. This may involve adding a new method, instance variable, or even a separate class.

1. Head 2. Body 3. Left arm 4. Right arm 5. Left leg 6. Right leg

Note: Hangman model (see other side of this page) has already been programmed to stop at 6 incorrect guesses (and because there is no human input, the game draw all 6 pieces).

// This controller starts a game when HangmanModel is constructed.

// This code also ensures HangmanPanel is observing the game.

public class HangmanMAIN extends JFrame {

public static void main(String[] args) {

new HangmanMAIN().setVisible(true);

}

private HangmanPanel hangmanPanel;

public HangmanMAIN() {

setTitle("Hangman");

setSize(250, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

hangmanPanel = new HangmanPanel();

add(hangmanPanel);

HangmanModel game = new HangmanModel();

game.addObserver(hangmanPanel);

}

}

// This simple HangmanModel has only one word that can be guessed at.

// And it makes the same guesses based on letters in a an array of char

public class HangmanModel extends Observable implements ActionListener {

private int numberWrong;

private String theWordToGuess;

private Timer timer;

private int tick;

public static final int MAX_WRONG = 6;

// This game will have the exact guesses each time. FOR DEMO ONLY

public static final char[] // Note: q is the last wrong guess

guesses = { 'a', 'e', 'i', 'o', 'u', 'y', 'x', 't', 'k', 'q' };

public HangmanModel() {

numberWrong = 0;

theWordToGuess = "polymorphism";

timer = new Timer(1000, this); // Make a "guess" every second

tick = 0;

timer.start();

}

public int numberOfWrongGuesses() {

return numberWrong;

}

// Return true if a guess (ch) is in the string "polymorphism"

// If not, add 1 to the number of wrong guesses

public boolean tryThisLetter(char ch) {

if (theWordToGuess.indexOf(ch) >= 0)

return true;

else {

numberWrong++;

return false;

}

}

// Every second, get the next character from guesses (an array of char)

// and try it. The time stops when MAX_WRONG incorrect guesses are made

// (and in this game with no user input, the guesses are always the same.

public void actionPerformed(ActionEvent timerTick) {

tick++;

if (numberOfWrongGuesses() >= MAX_WRONG)

timer.stop();

else {

char guess = guesses[tick];

System.out.println(guess +

" " + tryThisLetter(guess) +

" " + numberOfWrongGuesses());

// Tell the HangmanPanel to update the view

setChanged();

notifyObservers();

}

}

}

Using the provided code above, modify HangmanPanel below to do whatever you have to do to draw the correct number of pieces of the hangman in the order shown. This may involve adding a new method, instance variable, or even a separate class.

public class HangmanPanel extends JPanel implements Observer {

public HangmanPanel() {

}

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;

// Always draw the gallows and the noose at startup

g2.fill(new Rectangle2D.Double(5, 230, 200, 5)); // base of scaffold

g2.fill(new Rectangle2D.Double(5, 10, 5, 225)); // side of scaffold

g2.fill(new Rectangle2D.Double(5, 5, 80, 5)); // top of scaffold

g2.draw(new Line2D.Double(new Point(80, 10), new Point(80, 30))); // noose

public void update(Observable hangmanGame, Object ignored) {

}

}

Java Ranch Questions

Answer Questions for 7 after reading as many of the 161 questions as possible at http://www.javaranch.com/game/game2.jsp and reading these tips:

o  You should know most (except a few things like bit shifting, synchronized, volatile)

§  If the question feels really obscure, it probably won't be on the quiz

§  Specifically: there will be no bit operator questions--no need to know these operators

~(invert) <(shiftleft) >(right) &(and) ^(XOR) |(OR)

o  You may learn and/or relearn a few new things about Java

o  Topics you may need to further explore (inspired by Java Certification Questions)

§  Java 6's switch statement

int month = 8;

switch (month) {

case 1: System.out.println("January"); break;

case 2: System.out.println("February"); break;

// …

case 12: System.out.println("December"); break;

default: System.out.println("Invalid month.");break;

}

§  Overriding methods cannot throw new or broader exceptions

§  A static class can be used from outside the class. Example: Recangle2D.Double needs to be static in order to be instantiated outside of Rectangle2D

§  Java promotion: widening allowed (int to long as in long lg = 1234) , narrowing only with cast (double to float or float to int as in int i = (int)3.5f

§  Override private methods? No, but it looks that way when re-declared

§  Can't reduce scope when overriding methods. A protected method can be overridden as public, buy not reduced to package or private.

§  Division by 0 different for ints vs. doubles 5/0 is an error, 5.0/0 evaluates to infinity

§  A finally block always executes after the try and/or catch block finishes, even if there is no exception thrown. This allows cleanup code to always execute

ServerSocket ss = new ServerSocket(0);

try {

Socket socket = ss.accept();

// ...

}

finally {

ss.close(); // frees the port for later use no matter what happens in try

}

§  post increment, pre increment during assignment.

int y = 3;

int x = 0;

x = y++;

assertEquals(3, x);

assertEquals(4, y);

x = ++y;

assertEquals(5, x);

assertEquals(5, y);

7. Check the correct answer with an X, 1 point each (there will be ~28 questions)

a. All Java keywords are written in lower case.
__tr __false

b. Does a call to System.gc() force garbage collection to take place?

__ yes always __ not always

c. Assume: byte a = 3; byte b = 2; byte c; What is the result of c = a + b;

____ compile time error

____ c == 5

____ c == 3

____ runtime exception

d....

8. Choose the better design and explain why it is a better design

a) Which is the better design for a Stack Class, a or b? Why?

a Stack
empty()
push()
Object pop()
Object getTop() / b Stack
isEmpty()
push()
Object pop()
Object getTop()

b) Which code is safer, a or b? Why?

a
public String _name
b
private String _name;
public String getName() {return _name;}
public void setName(String arg) {_name = arg;}

c) Which method is better for returning a Fibonacci number from 1 to n, a or b? Why?

a
private int fibonacci(int n) {
if(n <= 2)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
} / b
private int fibonacci(int n) {
int sum = 1;
int older = 1;
int old = 1;
for (int next = 2; next < n; next++) {
sum = old + older;
old = older;
older = sum;
}
return sum;
}

d) Which code fragment is more readable (easier to understand), a or b? Why?

a
if (date.before (SUMMER_START) || date.after(SUMMER_END))
charge = quantity * _winterRate + _winterServiceCharge;
else
charge = quantity * _summerRate;
b
if (notSummer(date))
charge = winterCharge(quantity);
else
charge = summerCharge (quantity);

e) ...

10