## CPSC 124, Fall 2001 Second Test, November 12

This is the second test in CPSC 124: Introductory Programming.

Question 1: For this problem, you should write a complete Java subroutine named min. It should have two parameters of type int, and it should return a value of type int. When it is called, the function should return the smaller of its two parameters. For example, min(3,7) would be 3.

```          public static int min( int x, int y ) {
if ( x < y ) {
return x;
}
else {
return y;
}
}
```

(Note: The modifiers public and static are not required for a correct answer. However, it is likely that this function would be static if it were really written to be used. It is also likely that it would be public, since it would only really make sense to write such a simple subroutine as part of a library of routines that will be used over and over. In fact, min is already defined in the Math class as a public static subroutine.)

Question 2: Assume that a simple class Date is defined as follows:

```      public class Date {
public int month; // Number between 1 and 12 giving the month.
public int day;   // Number between 1 and 31 giving the day.
public int year;  // Positive integer representing the year.
}
```

Show the Java code that you would use to declare a variable of type Date, construct an object for that variable to refer to, and set the month, day, and year in the object to represent the date November 12, 2001.

```            Date today;         // Declare a variable named "today" of type date
today = new Date(); // Set the variable to refer to a newly created object
today.month = 11;   // Set the month in the object to represent November
today.day = 12;     // Set the day in the object
today.year= 2001;   // Set the year in the object
```

Question 3: Write a paint() method for an applet that displays two sets of nested squares, like the ones shown below. In the applet, the first set of squares should be red and the second set should be blue. The size of the large squares should be 50 pixels.

Answer: Here is a typical correct answer. (Note that the y-coordinates in the two sets of rects must be the same to make the rects line up horizontally.)

```         public void paint( Graphics g ) {
g.setColor( Color.red );
g.drawRect( 10, 10, 50, 50 );
g.drawRect( 20, 20, 30, 30 );
g.setColor( Color.blue );
g.drawRect( 80, 10, 50, 50 );
g.drawRect( 90, 20, 30, 30 );
}
```

Question 4: Suppose that class Point2D already exists and includes instance variables named x and y, of type double. Write a class Point3D which is a subclass of Point2D and which includes an instance variable z, of type double, in addition to the instance variables x and y.

Answer: Directly from the class notes:

```         public class Point3D extends Point2D {
public double z;
}
```

Question 5: Consider this complete program for a simple applet:

```      import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Guess extends Applet implements MouseListener {
private boolean isRed = false;
public void init() {
}
public void mousePressed(MouseEvent evt) {
Graphics g = getGraphics()
if (isRed) {
g.setColor(Color.red)
isRed = false;
}
else {
g.setColor(Color.green)
isRed = true;
}
g.drawRect( evt.getX() - 20, evt.getY() - 10, 40, 20 );
}
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
}
```

Explain as fully as you can what this applet does. Don't explain the code. Explain how the user interacts with the applet and what the applet does in response.

Answer: This applet draws the outline of a rectangle each time the user presses the mouse at a point on the applet. The first rectangle is green, the second is red, the third is green, the fourth is red, and so on. The rectangle is positioned so that the point where the user clicks is at the exact center of the rectangle. The rectangle is 40 pixels wide and 20 pixels high.

Question 6: A variable in Java can be made into a named constant by declaring it to be final. What does "final" mean here, and why might a programmer want to use named constants? Describe at least one example where a named constant would be useful.

Answer: If a variable is declared to be "final", then the value of that variable cannot be changed from its initial value while the program is running. (You can change the initial value in the source code and recompile the program, but you can't use an assignment statement in the program to change the value of the variable.) There are several reasons to used named constants. One is for readability. It is easier to understand a program that uses a name such as WAIT_FOR_FIRST_ROLL instead of a literal number such as 1. A name is more meaningful than a number. Another reason to use a named constant instead of a number is that if the value of the constant has to be changed, it will only have to be changed on one line of the program, rather than having to change the number every place it is used in the program. For example, if the number of rows and columns in a grid are represented by named constants ROWS and COLUMNS, then the program can be modified to use a different number of rows and columns simply by changing the values of these constants.

Question 7: A subroutine is sometimes said to have a contract. Explain what is meant by the contract of a subroutine, and discuss how it relates to the idea of a black box.

Answer: If the subroutine is thought of as a black box, then the contract of a subroutine essentially describes the interface of the black box. That is, the contract consists of all the information you need to know in order to use the subroutine, but does not include any knowledge of what happens inside the subroutine. More specifically, the contract includes the syntactic information you need in order to call the subroutine: The name of the subroutine, the return type, and the number and types of parameters. The contract also includes the semantic information that you need in order to use the subroutine effectively. That is, it includes information about what task the subroutine accomplishes and what each parameter means.

Question 8: One of the fundamental concepts in object-oriented programming is polymorphism. Explain what is meant by polymorphism and what it has to do with objects, classes, and subclasses. Include an example in your discussion.

Answer: Polymorphism refers to the fact that different objects can respond to the same message in different ways. More exactly, a method call such as obj.method() can call different methods in various classes, depending on the actual type of object to which the variable obj refers. This can happen because a method in a class can be redefined in a subclass. For example, a Shape class might have a draw() method. This method might be overridden in subclasses such as Rectangle and Oval. If shape is a variable of type Shape, then shape could refer to an object that belongs to any of the classes Shape, Rectangle, or Oval. When shape.draw() is called, the method that is executed is the one in the appropriate class. If shape is a Rectangle, then shape.draw() presumably draws a rectangle. If shape is an Oval, then shape.draw() presumably draws an oval.

Question 9: What is null (in the context of Java programming)?

Answer: null is a special pointer value that doesn't point to anything. When the type of a variable is given by a class (or interface), then the variable can hold a pointer value that points to an object. If the value of the variable is null, it just means that the variable is not currently pointing to any object.

Question 10: What is a local variable ?

Answer: A local variable is one that is declared inside a subroutine. A local variable can only be used inside the subroutine where it is declared, and it is invisible to the rest of the program.

Question 11: Graphical User Interface programs are usually event-driven and can often be thought of as state machines. Discuss the concepts of event and state, explain how they are related, and explain why they are used in GUI programs. Include some examples in your discussion. (This is a 15-point essay question.)

Answer: An "event" is something that happens outside the control of a program, usually because of some kind of user interaction such as clicking the mouse or pressing a key on the keyboard. In Java, an object can "listen" for various types of events, including mouse events, keyboard events, and higher-level events such as button-clicks. The user determines the order in which the events occur.

GUI programs tend to be event-driven because the user can take a variety of actions at any given time, and the program must be prepared to respond to these actions. This is different from a command-line program where the interaction with the user is carefully scripted and proceeds linearly from beginning to end. This can make writing GUI programs very different from writing command-line programs.

When a GUI program responds to an event, its response can depend on the "state" of the program, which is represented by values stored in the program's variables. For example, in a Craps game, the response to a click on a "Roll" button would depend on whether the user is rolling the dice for the first time in a game or is trying to make the "point" rolled on the first roll. As part of the processing of an event, the state of the program can change. This setup -- the state determines the response to some input, and the state can change as part of the response -- is a "state machine." GUI programs are often designed as state machines.

David Eck, eck@hws.edu