-
Page 1 of 23
School of Computer Science
0360-212 Object-oriented programming using JAVA
Winter 2005 Final Examination Duration: 3 hours
Student information Last name ______________________
First name _____________________
Student ID# _____________________
Lab section ____________________
University regulations: conduct during the examination
i) A candidate must not give assistance to or receive assistance
from, or communicate in any manner with any person other than the
Presiding Examiner or invigilator, or copy, or have at the
examination unauthorized aids of any kind. (This includes the use
of cell phones and pagers.) A candidate who is involved in such
activity will be subject to the disciplinary procedures of the
University according to Senate Bylaw 31.
ii) Eating, drinking and smoking are not permitted in
examination rooms. Personal recording/playback devices are not
permitted in the examination room. iii) If it is necessary for a
candidate to leave the room he or she may do so and return if
accompanied by the Presiding Examiner or an invigilator.
iv) A candidate must not write on any paper, other than that in
the answer book, and must keep all papers on the desk.
Students are allowed to take two textbooks on Java. No computers
allowed.
All answers must be given in this booklet.
Part I Part II Part III Total /20
/ 20
/60
/100
-
Page 2 of 23
Answer Sheet for Part I and Part II. You must answer all the
questions in part I and Part II on this page. Part I: True/False
Questions. Question # 1 2 3 4 5 Answer Question # 6 7 8 9 10 Answer
Part II: Multiple Choices. Question # 1 2 3 4 5 Answer Question # 6
7 8 9 10 Answer
-
Page 3 of 23
Part I True/False 20 marks For this part, clearly indicate if
each assertion is TRUE or FALSE. You must write TRUE or FALSE, NOT
T or F. 1. An interface reference can refer to any object of any
class that implements
the interface. T
2. A try block must have at least one catch block, but could
have many catch blocks, and may or may not have a finally block.
F
3. If classes C1 and C2 both implement an interface Cint, which
has a method whichIsIt, and if C1 c = new C1( ); is performed at
one point of the program, then a later instruction c.whichIsIt( );
will invoke the whichIsIt method defined in C1. F
4. All parts of a container in BorderLayout must be used.
F 5. If a GUI container is resized by the user, all components
of the GUI are
automatically increased or decreased by the same fraction to fit
in the newly sized container. F
6. A constructor may contain a return statement so long as no
value (or
expression) is returned. T
7. In order to handle a MouseEvent, one must implement either
the MouseListener or MouseMotionListener interfaces, or both. F 8.
An inner class is allowed to access directly all the instance
variables and
methods of its enclosing class. T
9. One can always extends an existing class to produce a
subclass.
F 10. The font of the text of a button can be changed using the
setFont() method.
T
-
Page 4 of 23
Part II Multiple Choice Questions 20 marksFor this part, please
note that each question below has only one answer. Choose the best
answer. 1. What is the output of the following program?
public class Inherit { class Figure { void display( ) {
System.out.println("Figure"); } } class Rectangle extends Figure {
void display( ) { System.out.println("Rectangle"); } } class Box
extends Rectangle { void display( ) { System.out.println("Box"); }
} Inherit( ) { Figure f = new Figure( ); Rectangle r = new
Rectangle( ); Box b = new Box( ); f.display( ); f = r; ((Figure)
f).display( ); f = (Figure) b; f.display( ); } public static void
main(String[ ] args) { new Inherit( ); } }
-
Page 5 of 23
A. Figure Rectangle Box
B. Figure Figure Figure
C. Figure Rectangle Figure
D. Rectangle
Figure
E. The program will not compile, therefore, no output.
A 2. An abstract class
A. is a class which cannot be instantiated B. is a class which
has no methods C. is a class which has only abstract methods D. is
a class which has only overridden methods
A For questions 3 5, use the following skeletal code.
public class ExceptionThrowerCode{ public void m1( ) { }
public void m2( ) { try{ m3( ); } catch(ArithmeticException ae)
{} catch(NullPointerException npe) {} } public void m3( ) { try{ }
catch(ArithmeticException ae) {} }
public static void main(String[ ] args){ try {
ExceptionThrowerCode etc = new ExceptionThrowerCode( ); etc.m1(
); etc.m2( );
} catch (ArithmeticException ae) { }
} }
-
Page 6 of 23
3. If an ArithmeticException arises in the try statement in m3,
A. it is caught in main B. it is caught in m1 C. it is caught in m2
D. it is caught in m3 E. it is not caught leading to the program
terminating
D 4. If a NullPointerException arises in the try statement in
m3,
A. it is caught in main B. it is caught in m1 C. it is caught in
m2 D. it is caught in m3 E. it is not caught leading to the program
terminating
C
5. If a NullPointerException arises in the try statement in m1,
A. it is caught in main B. it is caught in m1 C. it is caught in m2
D. it is caught in m3 E. it is not caught leading to the program
terminating
E 6. Which of ing statement best describes a Java program in a
file
named MyExam.java.
A. The file MyExam.java defines a class called MyExam. B. The
file MyExam.java defines a public class called MyExam. C. The file
MyExam.java defines a class which extends the class
Object. D. None of the above.
D 7. Consider the following method declared in a class whose
header is below: public myMethod() throws AnException
Which of the following statements is true? A. There must have a
try statement in the method myMethod. B. The exception AnException
must be a checked exception. C. The exception AnException was
thrown by a throw statement in
myMethod. D. None of the above.
D
-
Page 7 of 23
8. What is the output of running class Test?
A. ABCD B. BACD C. CBAE D. AEDC E. BEDC
E
public class Test { public static void main(String[] args) { new
Circle9(); } } public abstract class GeometricObject { protected
GeometricObject() { System.out.print("A"); } protected
GeometricObject(String color, boolean filled) {
System.out.print("B"); } } public class Circle9 extends
GeometricObject { /** Default constructor */ public Circle9() {
this(1.0); System.out.print("C"); } /** Construct circle with a
specified radius */ public Circle9(double radius) { this(radius,
"white", false); System.out.print("D"); } /** Construct a circle
with specified radius, filled, and color */ public Circle9(double
radius, String color, boolean filled) { super(color, filled);
System.out.print("E"); } }
-
Page 8 of 23
9. What happens when you attempt to compile and run these two
files in the same directory?
A. Both compile and P2 outputs "What a fancy method" when run.
B. Neither will compile. C. Both compile but P2 has an error at run
time. D. P1 compiles cleanly but P2 has an error at compile
time.
D 10. If you want to draw a red circle inside of a green square
in a JPanel where
the paintComponent method is passed a Graphics object called
page, which of the following sets of commands might you use?
A. B. page.setColor(Color.green); page.setColor(Color.red);
page.fillRect(50, 50, 100, 100); page.fillOval(60, 60, 80, 80);
page.setColor(Color.red); page.setColor(Color.green);
page.fillOval(60, 60, 80, 80); page.fillRect(50, 50, 100, 100);
C. D.
page.setColor(Color.green); page.setColor(Color.red);
page.fillRect(60, 60, 80, 80); page.fillOval(50, 50, 100, 100);
page.setColor(Color.red); page.setColor(Color.green);
page.fillOval(50, 50, 100, 100); page.fillRect(60, 60, 80, 80);
E. any of the above would accomplish this.
A
//File P1.java package MyPackage; class P1{ void afancymethod(){
System.out.println("What a fancy method"); } } //File P2.java
public class P2 extends P1{ public static void main(String argv[]){
P2 p2 = new P2(); p2.afancymethod(); } }
-
Page 9 of 23
Part III Programming Questions 60 marksALL JAVA CODE WRITTEN IN
PART III SHOULD BE COMMENTED. Question 1: 13 marks The following
program saved in the file Phone.java creates a GUI that resembles a
phone with functionality and logical error(s).
import java.awt.*; import java.awt.event.*; import
javax.swing.*; public class Phone extends JFrame {
private JButton keys[]; private JPanel keyPad, lcd; private
JTextArea lcdContent; private String lcdOutput = ""; private int
count = 0;
// constructor sets up GUI public Phone() {
super( "Phone" ); // set lcd layout to flow layout lcd = new
JPanel(); lcd.setLayout(new FlowLayout()); // initialize lcdContent
and add it to lcd panel lcdContent = new JTextArea( 4, 15 );
lcdContent.setEditable( false ); lcd.add( lcdContent ); keys =
new JButton[ 15 ]; // initialize all digit key Buttons for ( int i
= 3; i
-
Page 10 of 23
keys[ 0 ].addActionListener(new ActionListener() { public void
actionPerformed (ActionEvent e) { lcdContent.setText( " " );
lcdOutput = " Calling...\n\n " + lcdOutput; lcdContent.append(
lcdOutput );
} // end method actionPerformed } // end new ActionListener );
// end addActionListener call keys[ 1 ].addActionListener(new
ActionListener() { public void actionPerformed( ActionEvent e ) {
if ( lcdOutput.length() == 0 || lcdOutput.substring( 0, 1 ).equals(
"C" ) ) return; else { lcdOutput = lcdOutput.substring( 0, (
lcdOutput.length() - 1 ) ); lcdContent.setText( " " );
lcdContent.append( lcdOutput ); } // end else } // end method
actionPerformed } // end object ActionLstener ); // end
addActionListener call
keys[ 2 ].addActionListener(new ActionListener() { public void
actionPerformed( ActionEvent e ) { lcdContent.setText( " " );
lcdOutput = ""; } // end method actionPerformed } // end new
ActionListener
); // end ActionListener call for ( int i = 3; i
-
Page 11 of 23
// set keyPad layout to grid layout keyPad = new JPanel();
keyPad.setLayout( new GridLayout( 5, 3 ) ); // add buttons to
keyPad panel for ( int i = 0; i
-
Page 12 of 23
The above program compiles and runs. Answer each of the
following questions. a) If you are using a command line terminal
window on SOL to develop your java programs, write down the command
to compile the above program. (1 mark) Your answer: b) Draw
diagrams to show how the program works by following the sequence of
commands/actions issued by user. (6 marks, 2 marks each)
(i) The user first types java Phone on the command line. Your
answer:
(ii) After the command in (i), the user clicks the phone no.
2533000, then clicks send. Your answer:
(iii) Following the actions in (ii), the user clicks the Clr
button four times. Your answer:
-
Page 13 of 23
c) The program in this question contains a logical error. When
user dials a number, say, 2533000 and clicks send, the phone is
supposed to call the number 2533000 and this number is shown in the
phone display. However, at this point, if user continues to click
another digit, say 9, the phone display shows the number 25330009.
This means that during a phone call to 2533000, the phone user can
still change the number. This is a logical error. Modify this
program by changing ONE single existing statement in the event
handler for the Send button so that this logical error can be
eliminated. Show your change and explain why. Remember that you are
allowed to change only one SINGLE existing statement. (6 marks)
Your answer: Change the statement
lcdOutput = " Calling...\n\n " + lcdOutput; to
lcdOutput = "Calling...\n\n " + lcdOutput;
-
Page 14 of 23
Question 2: 15 marks Consider the classes MyClass,
MyExtendedClass and MyFinalClass.
public class MyClass{ public int v1; public int v2; public
MyClass(){ v1 = 1; v2 = 2; } public void method1(){
System.out.println("method1 in MyClass "+v1); } public void
method2(){ System.out.println("method2 in MyClass "+v2); } public
void method3(){ System.out.println("method3 in MyClass "+v2);
this.method2(); } }
public class MyExtendedClass extends MyClass{ public int v2;
public MyExtendedClass(){ v1=11; v2=22; } public void method2(){
System.out.println("method2 in MyExtendedClass "+v2);
this.method1(); } }
public final class MyFinalClass extends MyExtendedClass{ public
int v1; public MyFinalClass(){ v1 = 111; } public void method1(){
System.out.println("method1 in MyFinalClass "+v1); super.method1();
} }
-
Page 15 of 23
These classes, as well as the class Test given below, do not
contain errors. What is the output produced after running the
application Test?
public class Test{ public static void main(String args[]){
System.out.println("FIRST CASE"); MyClass obj1 = new MyClass();
obj1.method1(); obj1.method2(); obj1.method3();
System.out.println("SECOND CASE"); MyClass obj2 = new
MyExtendedClass(); obj2.method1(); obj2.method2(); obj2.method3();
System.out.println("THIRD CASE"); MyClass obj3 = new
MyFinalClass(); obj3.method1(); obj3.method2(); obj3.method3();
System.out.println("FOURTH CASE"); MyExtendedClass obj4 = new
MyFinalClass(); obj4.method2(); } }
-
Page 16 of 23
Your answer: FIRST CASE method1 in MyClass 1 ->0.5 method2 in
MyClass 2 -> 0.5 method3 in MyClass 2 ->0.5 method2 in
MyClass 2 ->0.5 SECOND CASE method1 in MyClass 11 -> 0.5 mark
method2 in MyExtendedClass 22 -> 1 marks method1 in MyClass 11
-> 1 mark method3 in MyClass 2 -> 0.5 mark method2 in
MyExtendedClass 22 -> 0.5 mark method1 in MyClass 11 -> 0.5
mark THIRD CASE method1 in MyFinalClass 111 -> 1 marks method1
in MyClass 11 -> 1 marks method2 in MyExtendedClass 22 -> 0.5
mark method1 in MyFinalClass 111 -> 0.5 mark method1 in MyClass
11 -> 0.5 mark method3 in MyClass 2 -> 0.5 mark method2 in
MyExtendedClass 22 -> 0.5 mark method1 in MyFinalClass 111 ->
0.5 mark method1 in MyClass 11 -> 1 mark FOURTH CASE method2 in
MyExtendedClass 22 -> 1 mark method1 in MyFinalClass 111 -> 1
mark method1 in MyClass 11 -> 1 marks
-
Page 17 of 23
Question 3: 12 marks File ParseInts.java below contains a
program template that should do the following:
z Prompts for and reads in a line of input z Takes the input
line one token at a time and parses an integer from
each token as it is extracted. z Sums the integers. z Prints the
sum.
For example, if you give it the input 10 20 30 40
it should print The sum of the integers on the line is 100.
However, if you try a line that contains both integers and other
words, e.g., We have 2 dogs and 1 cat.
You will probably get a NumberFormatException when it tries to
call Integer.parseInt on "We" if your program does not handle
exceptions. Use exception handling, complete this program so that
it always produces correct answer. For example, for the line of
input We have 2 dogs and 1 cat., your program should print
The sum of the integers on the line is 3.
//what do you want to import
public class ParseInts {
public static void main(String[] args) {
// Prompts for and reads in a line of input // Takes the input
line one token at a time and parses an integer from // each token
as it is extracted. // Sums the integers. // Prints the sum.
System.out.println("The sum of the integers on this line is " +
sum);
} }
-
Page 18 of 23
Your answer: //
**************************************************************** //
ParseInts.java // // Reads a line of text and prints the integers
in the line. // //
****************************************************************
import java.util.Scanner; public class ParseInts { public static
void main(String[] args) { int val, sum=0; Scanner scan = new
Scanner(System.in); System.out.println("Enter a line of text");
Scanner scanLine = new Scanner(scan.nextLine()); while
(scanLine.hasNext()) { try { val =
Integer.parseInt(scanLine.next()); sum += val; } catch
(NumberFormatException exception) { } } System.out.println("The sum
of the integers on this line is " + sum); } } // Prompts for and
reads in a line of input 2 marks
// Takes the input line one token at a time and parses an
integer from // each token as it is extracted, using proper
exception handling // Sums the integers. exception handling 4
marks,
the overall structure for handling each token using some kind of
loop structure 4 marks
// Prints the sum ->2 marks
-
Page 19 of 23
Question 4: 10 marks File IntList.java contains definitions for
a linked list of integers. The class contains an inner class
IntNode, which holds information for a single node in the list.
public class IntList { private IntNode front; //first node in
list public IntList(){ front = null; } public void addToFront(int
val){ front = new IntNode(val,front); } public void addToEnd(int
val){ IntNode newnode = new IntNode(val,null); if (front == null)
front = newnode; else { IntNode temp = front; while (temp.next !=
null) temp = temp.next; temp.next = newnode; } } public void
removeFirst(){ if (front != null) front = front.next; } public void
print(){ System.out.println("---------------------");
System.out.print("List elements: "); IntNode temp = front; while
(temp != null){ System.out.print(temp.val + " "); temp = temp.next;
} System.out.println("\n---------------------\n"); }
-
Page 20 of 23
Add the following two public methods to the IntList class. 1.
public void printRec()prints the list from first to last using
recursion. 2. public void printRecBackwards()prints the list from
last to first using
recursion. Note you can not change the headers of these two
methods although you may want to write other methods which
facilitate the writing of the above two methods. Your answer: 5
marks for each method each //Prints the list recursively. public
void printRec() { System.out.println ("\nList Elements...");
printRec(front); }
//---------------------------------------------------- //
Recursively prints the part of the list starting // starting at the
node pointed to by first.
//---------------------------------------------------- private void
printRec (IntNode first) { if (first == null) System.out.println();
else { System.out.print (first.val + " ");
printRec(first.next);
private class IntNode{ public int val; //value stored in node
public IntNode next; //link to next node in list public IntNode(int
val, IntNode next){ this.val = val; this.next = next; } } }
-
Page 21 of 23
} } //---------------------------------------------------- //
Prints the list backwards using recursion.
//---------------------------------------------------- public void
printRecBackwards() { System.out.println ("\nThe list
backwards..."); printRecBackwards(front); }
//--------------------------------------------------- //
Recursively prints the part of the list starting // at the node
pointed to by first backwards.
//--------------------------------------------------- private void
printRecBackwards(IntNode first) { if (first != null) {
printRecBackwards(first.next); System.out.print(first.val + " "); }
}
-
Page 22 of 23
Question 5: 10 marks Write a Java program that can display the
windows shown below. The size of the frame is 200 by 150.
When user presses the button "Register", your program should
display a dialog window showing the contents of the name and email
JTextFields. When user presses the button "Clear", your program
should clear the two JTextFields for name and email. You only need
to handle the events for buttons. For the button "Register", you
should use inner class to handle the event. For the button "Clear",
you should use anonymous class to handle the event. Sample Answers:
import javax.swing.*; import java.awt.event.*; import java.awt.*;
import javax.swing.*; public class Register extends JFrame
implements ActionListener { JLabel name, email; JTextField
nameArea, emailArea; JButton okButton, clearButton; public
Register() { super("register me!"); // 0.5 mark for calling super.
Container c = getContentPane(); //optional statement if you are
using J2SE 5.0 c.setLayout(new FlowLayout()); // 0.5 mark for
setting up layout manager name = new JLabel( "Your Name:" ); c.add(
name ); // 0.5 mark for setting up label 1 // add(name) if J2SE
5.0
-
Page 23 of 23
nameArea = new JTextField( 10 ); c.add( nameArea ); // 0.5 mark
for setting up JTextfield 1 email = new JLabel( "Your email:" );
c.add(email ); //// 0.5 mark for setting up label 2 emailArea = new
JTextField( 10 ); c.add( emailArea ); // 0.5 mark for setting up
JTextfield 2 okButton = new JButton("Register");
okButton.addActionListener(new registerButtonHandler()); c.add(
okButton ); clearButton = new JButton("Clear");
clearButton.addActionListener( new ActionListener() { public void
actionPerformed( ActionEvent event) { nameArea.setText("");
emailArea.setText(""); } } ); // 3.5 marks for registering and
writing correct anonymous class event handler. c.add(clearButton );
setSize(200, 150); show(); } // 3 marks for registering and writing
correct inner class event handler. class registerButtonHandler
implements ActionListener{ public void actionPerformed( ActionEvent
event) { JOptionPane.showMessageDialog(null, "You clicked
OK==>"+nameArea.getText()+" and "+emailArea.getText()); } }
public static void main(String args[]) // 0.5 mark for proper main
method and frame setup (setSize, show, etc). { Register AFrame =
new Register(); } }
/ColorImageDict > /JPEG2000ColorACSImageDict >
/JPEG2000ColorImageDict > /AntiAliasGrayImages false
/DownsampleGrayImages true /GrayImageDownsampleType /Bicubic
/GrayImageResolution 300 /GrayImageDepth -1
/GrayImageDownsampleThreshold 1.50000 /EncodeGrayImages true
/GrayImageFilter /DCTEncode /AutoFilterGrayImages true
/GrayImageAutoFilterStrategy /JPEG /GrayACSImageDict >
/GrayImageDict > /JPEG2000GrayACSImageDict >
/JPEG2000GrayImageDict > /AntiAliasMonoImages false
/DownsampleMonoImages true /MonoImageDownsampleType /Bicubic
/MonoImageResolution 1200 /MonoImageDepth -1
/MonoImageDownsampleThreshold 1.50000 /EncodeMonoImages true
/MonoImageFilter /CCITTFaxEncode /MonoImageDict >
/AllowPSXObjects false /PDFX1aCheck false /PDFX3Check false
/PDFXCompliantPDFOnly false /PDFXNoTrimBoxError true
/PDFXTrimBoxToMediaBoxOffset [ 0.00000 0.00000 0.00000 0.00000 ]
/PDFXSetBleedBoxToMediaBox true /PDFXBleedBoxToTrimBoxOffset [
0.00000 0.00000 0.00000 0.00000 ] /PDFXOutputIntentProfile ()
/PDFXOutputCondition () /PDFXRegistryName (http://www.color.org)
/PDFXTrapped /Unknown
/Description >>> setdistillerparams>
setpagedevice