Vous êtes sur la page 1sur 22

CS 180 Fall 2005 Final Exam

There are 40 multiple choice questions. Each one is worth 2 points. There are 6
programming questions. Each one is worth 20 points.
Answer the multiple choice questions on the bubble sheet given and the programming questions on the
exam booklet.
Fill in the Instructor, Course, Signature, Test, and Date blanks. For "Instructor" put your Recitation
Instructor's last name. For "Course" put CS 180. For "Test" put Final.
08:30 recitation in REC 122: Matt Carlson
08:30 recitation in BRNG B254: Andy Scharlott
09:30 recitation in BRNG B268: Nick Sumner
11:30 recitation in REC 308: Rimma Nehme
01:30 recitation in UNIV 103: Alvin Law
Fill in the bubbles that correspond to your name, section and student ID in the bubble sheet. For your
section number, use 0830, 0930,1130, or 0130 -- based on the start time of your Friday recitation.
For your student ID, use the 10 digit ID number on your student ID card. DO NOT USE YOUR SOCIAL
SECURITY NUMBER!
Exams without names will be graded as zero. Only the answers on the bubble sheet will be counted.
The questions will be discarded.

For the programming questions create a Java class that would compile without error.
Comments are nice, but are not required.

Recitation Start Time: _________________________________


Student Last Name: __________________________________
Student First Name: __________________________________

Multiple Choice Questions (2 points each):


1. Which of the following statements regarding Java is false?
a.
b.
c.
d.

Java uses a compiler


A Java program compiles into machine language
Java uses an interpreter
Java is a programming language

2. Which of the following is a legal variable name in Java?


a.
b.
c.
d.

1stInput
long
NumberOfPlayers
player.1

3. What is the output produced by the following code?


int n = 2;
System.out.print((++n) + " " + (n++) + "\n");
System.out.println(n);
a. 2 3 4
b. 3 3 4
c. 3 3
4
d. 2 3
4
4. What is the output produced by the following code?
String temp = "Hello CS180 Class";
System.out.print(temp.substring(8).trim());
a.
b.
c.
d.

180Class
180 Class
Hello CS
Nothing - this causes a compiler error

5. In a Java program, you read the following statement that compiles and executes.
Cookie cookie = new Cookie("chocolate chips");
What can you conclude?
a. Cookie is the name of a class.
b. cookie is a primitive type variable.
c. The Cookie class must have a constructor that has one formal parameter of
type String.
d. a and c

6. Which of the following while loops is equivalent to the do-while loop? Hint: you
may want to draw a flow chart to figure out the answer.
do
{

y = x + 7;
x++;
} while (x < 9);
a. y = x + 7;
x++;
while (x < 9)
{
y = x + 7;
x++;
}
b. while (x < 9)
{
y = x + 7;
x++;
}
y = x + 7;
x++;
c. while (x <= 9)
{
y = x + 7;
x++;
}
d. Both a and b
7. How many times is the phrase "Happy New Year" printed by the following code?
int a = 6;
int b = 12;
while (a < b)
{
System.out.println("Happy New Year");
a += 2;
b -= 2;
}
a.
b.
c.
d.

1
2
3
4

8. A constructor ...
a.
b.
c.
d.

must have the same name as the class it is declared within.


is used to create objects.
may be declared private
All of the above

9. Which of the following is a valid constructor header for a HousePet class:


a.
b.
c.
d.

public
public
public
public

HousePet HousePet()
void HousePet()
HousePet()
void HousePet( int numLegs )

10. Suppose you have a class with a method,


public int average( int first, int second )
Which of the following methods cannot be added to the class?
a.
b.
c.
d.

public
public
public
public

double
double
double
double

average(
average(
average(
average(

int first, int second, int third )


int first, int second )
double first, double second )
int[] numbers )

11. What is the type of an array initialized with the following value?
{ { {59.385}, {49.6} }, { {986.35}, {583.64}, {12.85} } }
a.
b.
c.
d.

double [][][]
double [][]
double [[]]
int[][]

12. What is the result of the following method?


public static void printStrings()
{
Integer[] num = new Integer[5];
Integer sum = 0;
for ( int index = 0; index < num.length; ++index )
sum += num[index];
System.out.println( sum );
}
a.
b.
c.
d.

"null" is printed
"0" is printed
A java.lang.ArrayIndexOutOfBoundsException is thrown
A java.lang.NullPointerException is thrown

13. Which of the following is added by the Java compiler as the first statement in
class B's constructor?
public class B extends A {
private int num;
public B() {
num = 0;
}
...
}
a.
b.
c.
d.

super()
A()
this()
nothing is added automatically

14. Which best describes overloading and overriding?


a. In
In
b. In
In
c. In
d. In

overloading, methods must have the same signature.


overriding, methods must have different signatures.
overloading, methods must have different signatures.
overriding, methods must have the same signature.
overloading and overriding, methods must have different signatures.
overloading and overriding, methods must have the same signature.

15. Given ...


public void methodA() throws Exception1, Exception2, Exception3
Which of the following can override methodA() in a derived class?
a.
b.
c.
d.

public
public
public
public

void
void
void
void

methodA()
methodA()
methodA()
methodA()

throws
throws
throws
throws

Exception4
Exception3
Exception1, Exception2, Exception3, Exception4
Exception1, Exception4

16. When defining a method you must include a ___________ to declare any exception
that might be thrown but is not caught in the method.
a.
b.
c.
d.

try block
finally block
catch block
throws-clause

17. Aside from the Scanner class, which of the following classes can be used for
text-file file input?
a.
b.
c.
d.

BufferedReader
ObjectInputStream
StringTokenizer
none of the above

18. With a BufferedReader, which of the following is true when the readLine() method
is called when the end of the file is reached?
a.
b.
c.
d.

the String returned is null


the String returned is the empty string, ""
the String returned is "EOF"
an IOException is thrown

19. Which of the following are reasons to close a file as soon as possible after its
use?
I. Closing a file prevents the file from accidentally being corrupted.
II. Closing a file which a program has written to will allow a BufferedReader
to open the file at a later time and read the written information.
III. Closing a file will prevent the file from accidentally being deleted by the
operating system.
a.
b.
c.
d.

I only
II only
I and II only
I and III only

20. Using the read() method in class BufferedReader returns an int.


following is true about the int returned?

Which of the

I. The int represents the actual integer in the file being read.
II. The int represents the ASCII value of the character in the file being read.
III. The int represents the end of file marker if the int returned is -1.
a.
b.
c.
d.

I only
II only
III only
II and III only

21. Which of the following is the correct way to create a vector to hold Strings
with an initial capacity of 10 items?
a.
b.
c.
d.

Vector v<String>
Vector<String> v
Vector v<String>
Vector<String> v

=
=
=
=

new
new
new
new

Vector<10>;
Vector[10];
Vector<String>(10);
Vector<String>(10);

22. Which of the following statements is true regarding Vectors with no specified
base type?
a.
b.
c.
d.

A base type is needed because Java needs to know how to allocate memory
No base type is needed because Java will use the Object class as a base type
If a base type is not specified the code will not compile
No base type is needed because Vectors default to storing String objects

23. Given a singly-linked list that contains Strings (as defined in the book and
class), what will the following code segment do? Note: head points to the head
of the list and the list contains at least 2 nodes.
ListNode curNode = head;
do
{
System.out.println(curNode.data);
curNode = curNode.next;
}
while(curNode != null);
a.
b.
c.
d.

Print out
Print out
Nothing Nothing -

the data of each item on the list


the data of the head node only
this will cause a compile error
this will cause an ArrayIndexOutOfBounds exception.

24. Given the following generic class, which of the statements will compile?
public class Sample<T>
{
private T data;

}
a.
b.
c.
d.

public void setData(T new)


{
data = new;
}
public T getData()
{
return data;
}

Sample<int> a = new Sample<int>();


Sample<String> b = new Sample<String>();
Sample<String> c = new Sample<String>;
Sample<double> d = new Sample<double>;

25. Which of the following is false regarding recursion and iteration?


a. Any recursive method can be rewritten in an iterative form (with a loop)
b. Recursive calls take time and consume additional memory
c. In general, recursive algorithms lead to better performance than iterative
algorithms
d. A recursive method is a method that calls itself

26. What is the value of doSomething(2,3) given the following code fragment?
public int doSomething(int a, int b)
{
if (b==1)
return a;
else
return a + doSomething(a,b-1);
}
a.
b.
c.
d.

2
4
6
the program generates a run time error (infinite recursion)

27. Select the recursive function which defines the sequence 5, 8, 11, 14, 17, 20 ..
a. public int s(int n)
{
if (n == 0)
return 5;
else
return (s(n) + 3);
}
b. public int s(int n)
{
if (n == 0)
return 5;
else
return (3*n + 5);
}
c. public int s(int n)
{
if (n == 0)
return 5;
else
return s(3*n + 5);
}
d. public int s(int n)
{
if (n == 0)
return 5;
else
return 3 + s(n-1);
}
28. Which method call will display a JFrame object named myFrame on the screen?
a.
b.
c.
d.

myFrame.showToScreen()
myFrame.display()
myFrame.setEnabled( true )
myFrame.setVisible( true )

29. Consider the following function


void RecEm(int i)
{
if ( i < 8 )
{
RecEm(i);
}
}
How many times is RecEm invoked by the function call RecEm(3) ?
a.
b.
c.
d.

2
5
7
This is an example of infinite recursion.

30. What method is used to respond to such things as button clicks?


a.
b.
c.
d.

public
public
public
public

void
void
void
void

actionHeard( ActionEvent a )
actionPerformed( ActionEvent a )
actionListener( Action a )
actionHeard( ActionListener a )

31. Suppose you need to create a GUI with the following design:

A stretches horizontally and has a fixed height.


B stretches vertically and has a fixed Width.
C takes up as much space as possible in all directions.
What is the best single Layout to use?
a.
b.
c.
d.

BorderLayout
GridLayout
FlowLayout
CardLayout

32. How might you extract a number from a JTextField object named text?
a.
b.
c.
d.

int
int
int
int

n
n
n
n

=
=
=
=

text.getValue()
text.getInt()
text.parseInt()
Integer.parseInt( text.getText() )

33. What does the trim() method do?


a.
b.
c.
d.

returns
returns
returns
shrinks

a string with all blanks removed


a string with leading blanks removed
a string with leading and trailing blanks removed
the capacity of the vector down to the current size of the vector

34. Given the following class,


public class Demo extends JFrame implements ActionListener {
...
Container contentPane = getContentPane();
JButton button = new JButton("button");
...
}
Which of the following correctly adds the button to the frame?
a.
b.
c.
d.

contentPane.add(button);
add(button);
Demo.add(button);
add(button, BorderLayout.NORTH);

35. In an applet-class definition, the ________ method takes the place of the
constructor.
a.
b.
c.
d.

paint()
init()
main()
run()

36. What method must appear in Demo given the following declaration?
public class Demo extends JFrame implements ActionListener
a.
b.
c.
d.

windowClosed()
actionPerformed()
getActionCommand()
addActionListener()

37. In a Java GUI, the purpose of classes which implement the ActionListener
interface is to:
a.
b.
c.
d.

describe the graphical display of GUI items such as JButtons


control the organization of items displayed in the GUI
respond to the events caused by GUI items such as JButtons
none of the above

10

38. Which of the following statements is true when comparing the pros and cons of
using an array versus using a java Vector?
I. An array is fixed in length when declared whereas a Vector is dynamic in
size and can be resized.
II. An arrays values can be indexed easily with the [] brackets. There
exists no such equivalent for a Vector.
III. A Vector can store objects of any type where as an array can only store
primitive types.
a.
b.
c.
d.

I only
II only
II and III only
I and II only

39. Given the method definition below, what is the result of calling f(3, 5)?
public int f(int x, int y)
{
if (x < 0 || y > 10)
return x + y;
else
return f(x-1, y+1);
}
a.
b.
c.
d.

2
8
10
the method call f(3,5) will not terminate

40. Which of the following is true about the use and purpose of the Iterator
interface?
I. An iterator allows a programmer to efficiently search for an element in a
java Vector.
II. An iterator allows a programmer to perform a set operation on each element
of a data structure such as a java Vector or a linked list.
III. An iterator provides an easy way to sort the elements of a Vector or
linked list.
a.
b.
c.
d.

I only
II only
III only
II and III only

11

Programming Questions (20 points each):


1. You work for a company which produces different types of widgets. Occasionally a widget is produced which is
defective. Your boss would like you to write a program, RatioCalculator, which computes the ratio of widgets
produced to defective widgets. The input to the program will be from the user, and the program should work as
follows:
1. Input the total number of widgets produced.
2. Input the total number of defective widgets produced.
You should implement:
public double divide( int num, int den ) { ... }
to compute the ratio of widgets produced to defective widgets produced.
You should write two Exception classes:
1. DivideByZeroException - thrown if trying to divide by 0
2. NegativeNumberException - thrown if a negative number is given as input
If a ratio can be computed successfully, you should output the ratio as shown in the sample execution.
Be sure to print "End of Program" at the very end of your program.
Three sample runs of the program are given below:
Enter number of widgets produced:
1000
How many were defective?
500
One in every 2.0 widgets is defective.
End of Program
Enter number of widgets produced:
-10
Cannot have a negative number of widgets.
End of Program
Enter number of widgets produced:
1000
How many were defective?
0
Congratulations! A perfect record!
End of Program

12

13

2. You are asked to do a survey of the holiday spending for this Christmas. Write a complete Java program that will
allow a user to enter a set of budgeted spending and calculate some basic statistics. The integer spending
amount will be entered from the keyboard, and you do not know in advance how many entries will be entered.
After all budgets have been entered (the user will enter -1 to signal end of input), display the integer mean
(average), high budget, and low budget.
Note: You can assume that all input are valid (you do not need to test for non-integers). Only -1 to signal end
of input will be out of range. You can also assume that at least one number will be entered.
You must use the Vector class to store the set of numbers so that you can expand your program later to include
other statistics.
Sample execution:
Enter
Enter
Enter
Enter
Enter

budget
budget
budget
budget
budget

(-1
(-1
(-1
(-1
(-1

to
to
to
to
to

finish):
finish):
finish):
finish):
finish):

100
75
37
82
-1

Average Budget: 73
High Budget: 100
Low Budget: 37

14

15

3. Assume we have a class called Node which can be used to build a linked list. Each Node contains an array of
integer scores that are within a certain range. For example you may use the 1st Node to store all the scores in
the F range, the 2nd Node to store all the scores in the D range, the 3rd Node to store all the scores in the C
range, etc. A Node contains the following variables and methods:
class Node
{
private int[] values; // these values are sorted in ascending order
private Node next;
public
public
public
public
public

Node(int[] values, Node next)


int[] getValues()
void setValues(int[] values)
Node getNext()
void setNext(Node next)

Now, complete the class Gradebook below. Gradebook contains a linked list of the above Node class. Each
node represents a non-overlapping group of grade values and each successive Node contains a range of group
values greater than the previous Node. For this problem, you will not be responsible for constructing the
Gradebook itself; you may assume the Gradebook is properly constructed for you already. You only need to
complete the method gradeExists(int), which returns true if the grade exists within the Gradebook, and false
otherwise. Since the values array is sorted, you should take advantage of this and perform a binary search for
the specified value. Points will be deducted for inefficient algorithm. You may assume the Gradebook
contains at least one grade value in one Node (that is, the variable gradebook is never null). You may write
helper methods as needed.
class Gradebook
{
Node gradebook;
/**
* You dont need to bother with constructors and other methods
*/
/**
* TODO: complete the method gradeExists
* use binary search to look for grade in the linked list
* return true if grade is found, false otherwise
*/
public boolean gradeExists(int grade)
{

16

17

4. Write a RECURSIVE method to determine whether a given string is a palindrome or not. A string is a
palindrome if it reads the same forward and backward. You can assume the given string will contain only
alphabetical characters. Ignore the case of the letters and skip over blanks when you make the comparison. For
example:
The word cow is not a palindrome.
The phrase A man A plan A canal Panama is a palindrome.

18

5. Given that JLabels have some interesting features, it would be nice to be able to try out various possible
JLabels without making a new program each time. Thus, you are to create a complete Java GUI program that
allows the user to enter the text of JLabels, possibly with multiple lines, and then preview them. You should
use the following design:
Title

Enter Text:

Label Preview:
Label Preview

Text Area

Button
The user can enter text in the text area. Then, when the button is pushed, this text is displayed as a label in the
label preview. Note that there is a title label at the top, as well as a label for both the text entry and label
preview regions. Also, the text entry and preview regions are the same size. In addition, the button is centered
and does not take up more space than its text needs.
The text area should wrap words around lines, but does not need to consider scrolling.

19

20

6. New York Times keeps two sorted lists for the most popular fiction books and non fiction books based on the
number of copies sold. These are stored in two text files TopFictionBooks.txt and TopNonFictionBooks.txt.
Each file contains a list where each line follows the format of:
Title, Author, copies sold
Title contains multiple words separated by blanks and no punctuations. Author contains first name followed by
last name. It may also contain initials. Copies sold is an integer. The three fields are separated by commas.
Write a MergeList class that will open both files and print to the screen the merged result of the two lists
showing the title, the author, and the number of copies sold from the most popular to the least popular. You
should handle common file errors such as FileNotFound or IOException by printing a message and exiting.
You can assume the lists are not empty and the entries are properly formatted.
Sample data for TopFictionBooks.txt:
Mary Mary, James Patterson, 34567
At First Sight, Nicholas Sparks, 32400
Light from Heaven, Jan Karon, 30123
Predator, Patricia Cornwell, 28100
The Lighthouse, P. D. James, 28049

21

22

Vous aimerez peut-être aussi