You are on page 1of 7

CMPSC 221

Object-Oriented Programming with Web Applications


Fall 2011

Exam I: Object-Oriented Programming


September 29, 2011
Name: ____________KEY________________________________

Last 4 digits of ID: ____ ____ ____ ____

Honor Code Statement


I certify that I have not discussed the contents of the exam with any other student and I will not
discuss the contents of this exam with any student in this class before it is returned to me with a
grade. I have not cheated on this exam in any way, nor do I know of anyone else who has cheated.
Signature: _________________________________________________________

Directions/Notes:

Write your ID on every page of this exam. Write your name just on this cover page.

No notes, books, or calculators are permitted.

Be sure to sign the honor code statement when you are finished.

Answer each conceptual question completely, clearly, and concisely.

All questions on this exam are implicitly prefaced with As taught in CMPSC 221 lectures this
term.

In coding problems, you may assume all import statements needed have been provided and you
may always assume you have in scope a properly-initialized Scanner object called input to
read from the console.

No comments are required in coding problems unless explicitly required. They may be added to
clarify assumptions (as long as assumptions don't circumvent the problems at hand).

The points intentionally add up to more than 100 possible.

Score Breakdown:
#

10

11

12

13

Total

11

39

100

Score

Value

CMPSC 221 / Fall 2011 / Exam 1 - Page 2 of 7

1.

Last 4 Digits of Student ID Number: ___ ___ ___ ___

Suppose we have a block of code that contains the possibility there's a file that won't be found, a division by zero, any
kind of input/output problem, and an uninitialized reference variable. List the exceptions you must catch in an
appropriate order and explain why you chose the order you did.
[4 pts.]
We must catch more specific exceptions before more general exceptions because only the first catch block that "fits" is
executed.
Thus, we must catch FileNotFoundFoundException before IOException because the former is a subclass of
the latter and we must catch Exception at the end because it is the most general kind of exception.
Exceptions ArithmeticException and NullPointerException fit in anywhere else
(Day 12 / Lab 9)

2.

What is the difference between overriding and overloading?

[3 pts.]

Overriding occurs when we have a method in a superclass and we implement a method with the same name and
parameters in a subclass to do something more specific in the subclass. Overloading occurs when we make a second
method with the same name as an existing method within the same class, but with a different parameter list. (The
odd caveat: we could, in a subclass, overload a method that's in a superclass as long as we've not overridden it.)
(Day 6)
3.

Describe a scenario where it would be appropriate to use a protected member function.

[3 pts.]

This would be appropriate if we have a method we wanted subclasses to be able to use, but not clients. Such a need
would arise if we wanted to make a method for some common computation used in subclasses to aid other
computations and which is independent of the specific subclass. (Day 6 and beyond)
4.

Why is it that we never write destructors in Java?

[2 pts.]

Java has a built-in automatic garbage collector that cleans up any unused dynamically-allocated objects. (Day 4)
5.

Explain how it would be possible to make an array containing a BankAccount, the integer 7, and a Trapezoid or
explain why it's not possible.
[3 pts.]
Since BankAccount and Trapezoid are reference type variables, they both inherit from Object, so they could
easily be stored in an array of type Object. The integer, if stored in an int, could not, because int is a primitive
type. However, we could get around this problem by storing the 7 in the wrapper class Integer, which is a
reference type, enabling us to store all of these rather unrelated things in an array of type Object. (Day 6, 2)

6.

7.

Define each term in as concise a way as possible.


a.

abstraction - focusing on the "what," not the "how" (Day 4)

b.

encapsulation - keeping related data and behavior in the same place (Day 4)

Fill in the blanks.


a.

The bytecode verifier is the part of the JVM responsible for making sure a program doesn't cause
security violations. (Day 1)

b.

The kind of class member function that changes the state of objects is modifiers. (Day 4)

c.

Allowing a class to inherit from more than one superclass is called multiple inheritance. (Day 9)

[4 pts.]

[3 pts.]

CMPSC 221 / Fall 2011 / Exam 1 - Page 3 of 7

8.

Last 4 Digits of Student ID Number: ___ ___ ___ ___

Consider the following list of classes that model parts of a programming language's syntax: CodeBlock,
ControlStructure, Switch, ForLoop, WhileLoop, SelectionStructure, LoopTest,
RepetitionStructure, IfElseBlock, UpdateStep. A CodeBlock is defined as the code that could be in
the body of any method; the meanings of the rest should be obvious from your programming experience. Your task is to
describe all of the is-a and has-a relationships between these classes.
[9 pts.]
a.

First, draw an inheritance hierarchy for all classes that fit.


ControlStructure
SelectionStructure

IfElseBlock

b.

RepetitionStructure

Switch

ForLoop

WhileLoop

Then fill in this chart, where the header of each row would begin each relationship and the header of each column
would end each relationship. Thus, if you believed the statement CodeBlock is a ControlStructure were
true, you'd write "is a" in the second column of the first row. Each block should say "is a" or "has a" or be left blank
if there is no relationship.

CodeBlock

Code
Block

Control
Structure

Switch

For
Loop

While
Loop

Selection
Structure

--

has a

has a

has a

has a

has a

Control
Structure

--

Switch

is a

ForLoop

is a

WhileLoop

is a

Selection
Structure

is a

--

Repetition
Structure

IfElse
Block

has a

has a

Update
Step

is a
--

--

has a

is a

has a

has a

is a

has a

--

has a

--

--

LoopTest

Repetition
Structure

is a

IfElse
Block

is a

UpdateStep

Loop
Test

has a
is a

--

--

It could also be argued that any ControlStructure has a CodeBlock in the body, so has a relationships would
be accepted for credit.
(Day 5, 6, 7, 8)

CMPSC 221 / Fall 2011 / Exam 1 - Page 4 of 7

9.

Last 4 Digits of Student ID Number: ___ ___ ___ ___

Implement this function used to determine the winner of a contest from an array of entries:

[6 pts.]

String getWinner(String[] emailAddresses)


// PRE: emailAddresses is filled such that each entry contains a proper email address
// POST: FCTVAL == an email address selected from emailAddresses at random, such that
//
any entry in emailAddresses is as likely as any other to be chosen
{
return emailAddresses[ (int)(Math.random()*emailAddresses.length) ];
// Math.random gives back a value >= 0 and < 1 and we need
//
to scale this value over valid places in the array.
// We also need to typecast to get a whole-number result.
} (Day 3 and your experience generating random integers for dice and prizes in Project 1)

10. Suppose you have three perfectly parallel arrays that store the food and supplies a catering company orders during a
typical week:
String[] products;
int[] quantities;
double[] unitCosts;

// each entry is the name of a food item or


//
supply ordered
// each entry is the number of units ordered of
//
the corresponding item in products
// each entry is the cost in dollars of one
//
unit of the corresponding product in products

These arrays store quantities for a typical week, but events during different seasons change the sales demand for the
company. Suppose, then, we also have a constant, EXPECTED_EXPENDITURES, that tells how much money (in
dollars) the manager expects to spend during a given week on ordering food and supplies. Assume that the when the
company has a higher sales week, it simply multiplies its order proportionally. For example, if during a typical week the
company spends $50 on plastic silverware and $100 on paper plates, it would spend $75 on plastic silverware and $150
on paper plates during a week when its expected expenditures were 1.5 times the normal amount.
Assuming that all three parallel arrays have been filled and are of the same size, initialize a fourth parallel array of type
int called quantitiesToOrder such that it contains how many of the corresponding product to order to get the
total amount spent as close to EXPECTED_EXPENDITURES as possible without ever going over budget (thus you
should always round down).
[8 pts.]
double sum;
double multiplier;

// total amount spent on purchasing quantities amount


//
of everything in unitCosts, in dollars
// fraction by which to multiply costs during a
//
typical week to get a total of
//
EXPECTED_EXPENDITURES dollars

// Compute how much we spend in a normal week


sum = 0;
for(int i = 0; i < quantities.length; i++)
{
sum += quantities[i]*unitCosts[i];
}
// Figure out how much to scale spending by
mutliplier = EXPECTED_EXPENDITURES/sum;
// Compute new costs to populate output array
quantities_to_order = new int[quantities.length];
for(int i = 0; i < quantities.length; i++)
{
quantities_to_order[i] = (int)(quantities[i]*multiplier);
}

(Day 2 and your experience with processing parallel arrays in Lab 3)

CMPSC 221 / Fall 2011 / Exam 1 - Page 5 of 7

Last 4 Digits of Student ID Number: ___ ___ ___ ___

11. Suppose we have abstract class BigCat, which has concrete subclasses Lion, Tiger, and Panther. Suppose we
have the following array:
BigCat[] cats = new BigCat[10];
Element 0 of cats is a Lion, element 1 is a Tiger, and element 2 is a Panther.
[11 pts.]
a.

Suppose there's an abstract method attack() defined in BigCat. Write a block of code to send a message to all
of the initialized elements of cats to attack.
for(BigCat cat : cats)
{
cat.attack();
}

b.

It is due to polymorphism that each BigCat has the ability to attack in a different way and due to dynamic binding
that the correct form of attack() happens for the correct BigCat when the code of part (a) executes.

c.

Explain why the following code is or is not valid:


cats[3] = new BigCat();
This code attempts to instantiate an abstract class, so it is not valid.

d.

Suppose class Lion has a method roar() that only exists in Lion, not any of the other subclasses. Send a
message to the Lion at position 0 in cats to roar.
((Lion) cats[0]).roar();

(Day 8 and your experience having to typecast with abstract classes in Project 1.)
12. Suppose class TVChannel models TV channels and has accessor getName() that returns the name of the TV channel
stored in each object. Suppose we have the following array:
TVChannel[] majorNetworks;
Suppose majorNetworks is full, i.e. every element contains meaningful data.
[9 pts.]
a.

Write a block of code that stores a comma-separated list of the names of the channels in majorNetworks in a
String variable channelNames.
channelNames = "";
for(int i = 0; i < majorNetworks.length; i++)
{
channelNames += majorNetworks[i].getName();

b.

if(i < (majorNetworks.length - 1))


channelNames += ", ";

// put comma after all but last in list

Justify your choice of loop in solving part (a).


We will need to iterate as many times as there are entries in majorNetworks and this array is full, so we know
how many times we'll iterate before the loop begins. Thus, we have a determinate loop. Although the logical
size and physical size match, we need to use the indices to the array to determine whether or not an element is
the last so we don't have a stray comma and space at the end of the list, so we must use a regular for loop.

(Part (a) was to be exactly the same thing as the comma-separated list in the Player class in the Project and Part (b)
comes from the whole review unit.)

CMPSC 221 / Fall 2011 / Exam 1 - Page 6 of 7

Last 4 Digits of Student ID Number: ___ ___ ___ ___

13. Suppose were are modeling a parking lot and have a class ParkingLot to do this. To help us out, we have a class
called ParkedVehicle, which is used to model vehicles that could park in the lot.
[39 pts.]
Suppose class ParkingLot contains the following data members:
private int numSpacesTotal;

private int numSpacesUsed;


private ParkedVehicle[] carsInLot;

a.

// how many parking spaces are in the lot,


//
including occupied and unoccupied spaces
// how many spaces are currently occupied
// the vehicles that are currently in the lot,
//
maintained contiguously with the first
//
numSpacesUsed array locations filled

Write a reasonable default constructor for the ParkingLot class. (Remember, no documentation - internal or
external - is required on this exam unless a problem explicitly requests it.)
[5 pts.]
public ParkingLot()
{
numSpacesTotal = 100;
numSpacesUsed = 0;
carsInLot = new ParkedVehicle[numSpacesTotal];
}

b.

// any positive value is accepted


(Day 4, 5)

Write a method removeVehicleAtIndex(), which takes as an input parameter an index to the array
carsInLot and which adjusts carsInLot such that the vehicle at the input index is effectively removed from
carsInLot, as per documentation of the class data members in the class data dictionary above.
[6 pts.]
public void removeVehicleAtIndex(int index)
// PRE: 0 <= index < numSpacesUsed
// POST: carsInLot[index..(numSpacesUsed-2)] contain what
//
carsInLot[(index+1)..(numSpacesUsed-1)] before the call,
//
and numSpacesUsed is one smaller than before the call
{
for(int i = index; i < numSpacesUsed-1; i++)
{
carsInLot[i] = carsInLot[i+1];
}
numSpacesUsed--;

(Day 4)

c.

Write the header for an initializer constructor that takes as input parameters any number of ParkedVehicle
objects that have been initialized and are in the lot as well as the capacity of the lot.
[2 pts.]
public ParkingLot(int capacity, ParkedVehicle... vehicles)

(Day 3)

Now suppose we want to consider a subclass of ParkingLot to model parking lots that charge parking fees. We'll call
this class PaidParkingLot.
d. Add whatever is necessary to complete the first line of code of the class definition of PaidParkingLot:
public class PaidParkingLot extends ParkingLot
e.

(Day 6)

Define a data member for the parking lot's hourly rate as you'd add it to the data dictionary of PaidParkingLot.
(This one requires documentation.)
[3 pts.]
private double hourlyRate;

f.

[2 pts.]

// cost per hour or fraction thereof in $


// to park in this lot

(Day 4)

Suppose we mandated that once a parking lot's hourly rate were set, it could not change. How would your response
to (e) change?
[1 pt.]
Make it final

(Day 5)

CMPSC 221 / Fall 2011 / Exam 1 - Page 7 of 7

Last 4 Digits of Student ID Number: ___ ___ ___ ___

[continues on next page...]


g.

Suppose that all PaidParkingLots are owned by the same company, and this company sometimes gives
discounted holiday rates. Define a data member as you'd add it to the data dictionary of PaidParkingLot, that
indicates whether or not it is a holiday. (The definition is not necessary this time.)
[3 pts.]
(Day 5)

private static boolean isHoliday = false;

h.

Suppose PaidParkingLot has a method turnHolidayRateOn() that essentially sets the data member you
defined in the last part to true. Suppose for this part only that you are working in client code and you have two
PaidParkingLots, beaverAveLot and fraserStLot. Write appropriate code to turn the holiday rate on for
both of these lots.
[3 pts.]
(Day 5)

PaidParkingLot.turnHolidayRateOn();

i.

Write an initializer constructor for PaidParkingLot that takes two input parameters: the parking lot's hourly rate
and how many spaces are in the lot.
[7 pts.]
public PaidParkingLot(double hourlyRate, int capacity)
{
super();
numSpacesTotal = capacity;
carsInLot = new ParkedVehicle[numSpacesTotal];

// reset # of spaces and the array

this.hourlyRate = hourlyRate;

h.

(Day 6)

Write a precondition for the method you just wrote.

[3 pts.]

// PRE:
//

i.

hourlyRate >= 0 and hourlyRate is in dollars,


capacity > 0

(Review and Day 5)

Write a method getFormattedHourlyRate() that returns a String containing a PaidParkingLot's


hourly parking rate, properly formatted.
[4 pts.]
public String getFormattedHourlyRate()
// POST: FCTVAL == String containing hourlyRate with 2 decimals and a dollar sign
{
return String.format("$%.2f", hourlyRate);
}
(Day 2 and 4)