Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
HONG KONG UNIVERSITY OF SCIENCE & TECHNOLOGY COMP 201: Java Programming Spring 2002 Midterm Examination 6:30-8:30 pm March 26, LTD Student Name: Email Address: Student Number: Lab Section/TA Name: Instructions: 1. 2. 3. 4. This is a close-book, close-note examination. Check that you have all 16 pages (including this cover page). Answer all questions in the space provided. Rough work should be done on the back pages. Don’t use pencils. Question Score / full score 1 /30 2 /25 3 /10 4 /10 5 /10 6 /15 Total /100 1 Question 1(30 marks; 3 marks for each correct answer): 1. A class design requires that a particular member variable must be accessible for direct access by any subclasses of this class, but otherwise not by classes which are not members of the same package. What should be done to achieve this? a. The variable should be marked public. b. The variable should be marked private. c. The variable should be marked protected. d. The variable should have no special access modifier. e. The variable should be marked private and an accessor method provided. Answer: ______________C_________________________________________ 2. Which statement is true about a non-static inner class? a. It must implement an interface. b. It is accessible from any other class. c. It can only be instantiated in the enclosing class. d. It must be final if it is declared in a method scope. e. It can access private instance variables in the enclosing object. Answer: _______________E________________________________________ 3. When you call a modifying method on a String, what happens to the original String? a. It is immediately destroyed and a new String is created and the reference is updated to point to the new String. b. It remains, a new StringBuffer object is created and returned. c. It remains, a new String is created and the reference is updated to point to that String. d. It is immediately destroyed, and a new StringBuffer object is created and returned. Answer: ________________C_______________________________________ 4. How can you initialize an array of two characters to 'a' and 'b'? a. char[] charArray = new char[2]; charArray = {'a', 'b'}; b. char[2] charArray = {'a', 'b'}; c. char[] charArray = {'a', 'b'}; d. None of the above. Answer: _________________C______________________________________ 2 5. FileInputStream fis = new FileInputStream("test.dat"); a. It creates a new file named test.dat if it does not exist and opens the file so you can write to it. b. It creates a new file named test.dat if it does not exist and opens the file so you can write to it and read from it. c. It creates a new file named test.dat regardless of whether it exists or not and opens the file so you can write to it. d. It creates a new file named test.dat regardless of whether it exists or not and opens the file so you can write to it and read from it. e. None of the above is correct. Answer: __________________E_____________________________________ 6. InputStream and OutputSteam are __________. a. The top-level abstract classes defined in the java.io package, from which all other stream classes inherit. b. The top-level abstract classes defined in the java.io package, from which all other byte stream classes inherit. c. Classes that you can instantiate to read and write bytes. d. Interfaces that define methods that can be used to read and write bytes. Answer: ___________________B____________________________________ 7. Which of the following statements is correct to create a DataOutputStream to write to a file named out.dat? a. DataOutputStream outfile = new DataOutputStream(new File("out.dat")); b. DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); c. DataOutputStream outfile = new DataOutputStream(FileOutputStream("out.dat")); d. DataOutputStream outfile = new DataOutputStream("out.dat"); Answer: ____________________B___________________________________ 8. Which of the following is not an advantage of Java exception handling? a. Java separates exception handling from normal processing tasks. b. Exception handling improves performance. c. Exception handling makes it possible for the caller's caller to handle the exception. d. Exception handling simplifies programming because the error-reporting and error-handling code can may be placed at the catch block. Answer:______________________B______________________________________ 3 9. Which of the following are true. Select all correct answers. a. A static method may be invoked before even a single instance of the class is constructed. b. A static method cannot access non-static methods of the class. c. Abstract modifier can appear before a class or a method but not before a variable. d. final modifier can appear before a class or a variable but not before a method. Answer:________________A B C_________________________________________ 10. Suppose s1 and s2 are two strings. Which of the following statements or expressions are incorrect? a. String s = new String("new string"); b. String s3 = s1 + s2; c. s1 >= s2 d. int i = s1.length(); Answer:____________________C________________________________________ 4 Question 2(25 mark): a) (5 marks) What gets displayed on the screen when the following program is compiled and run. public class Alias1 { int i; Alias1(int ii) { i = ii; } public static void main(String[] args) { Alias1 x = new Alias1(7); Alias1 y = x; System.out.println("x: " + x.i); System.out.println("y: " + y.i); System.out.println("Incrementing x"); x.i++; System.out.println("x: " + x.i); System.out.println("y: " + y.i); } } Answer: x: 7 y: 7 Incrementing x x: 8 y: 8 b)( 5 marks) What gets displayed on the screen when the following program is compiled and run. public class Alias2 { int i; Alias2(int ii) { i = ii; } static void f(Alias2 reference) { reference.i++; } public static void main(String[] args) { Alias2 x = new Alias2(7); System.out.println("x: " + x.i); System.out.println("Calling f(x)"); f(x); System.out.println("x: " + x.i); } } Answer: x: 7 Calling f(x) x: 8 5 c)(5 points) What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java 1"); int i = 1; int y = 2/--i; System.out.println("Welcome to Java 2"); } catch (RuntimeException ex) { System.out.println("Welcome to Java 3"); } finally { System.out.println("End of the block 1"); } System.out.println("End of the block 2"); } } Answer: Welcome to Java 1 Welcome to Java 3 End of the block 1 End of the block 2 6 d) (5 points) What is the output of the following program? import java.util.StringTokenizer; public class TestStringTokenizer { public static void main(String[] args) { String s = "I$am*learning Java."; StringTokenizer st = new StringTokenizer(s, "$*."); while (st.hasMoreTokens()) System.out.print(st.nextToken()+" "); } } Answer: I am learning Java _______________________________________________________ 7 e) (5 marks) What gets displayed on the screen when the following program is compiled and run. class Base { Base() { System.out.println("Message 1 : In the base class"); } } abstract class Derived1 extends Base { Derived1() { System.out.println("Message 2 : In the abstract class Derived1"); } } public class Derived2 extends Derived1 { public Derived2() { System.out.println("Message 3 : In the derived2 class"); } public static void main(String args[]) { Derived2 d2 = new Derived2(); } } Answer: Message 1 : In the base class Message 2 : In the abstract class Derived1 Message 3 : In the derived2 class _______________________________________________________ 8 Question 3. (10 marks) What gets displayed on the screen when the following program is compiled and run. class Egg2 { protected class Yolk { public Yolk() { System.out.println("Egg2.Yolk()"); } public void f() { System.out.println("Egg2.Yolk.f()"); } } private Yolk y = new Yolk(); public Egg2() { System.out.println("New Egg2()"); } public void insertYolk(Yolk yy) { y = yy; } public void g() { y.f(); } } public class BigEgg2 extends Egg2 { public class Yolk extends Egg2.Yolk { public Yolk() { System.out.println("BigEgg2.Yolk()"); } public void f() { System.out.println("BigEgg2.Yolk.f()"); } } public BigEgg2() { insertYolk(new Yolk()); } public static void main(String[] args) { Egg2 e2 = new BigEgg2(); e2.g(); } } Answer: Egg2.Yolk() New Egg2() Egg2.Yolk() BigEgg2.Yolk() BigEgg2.Yolk.f() 9 Question 4. (10 marks) What gets displayed on the screen when the following program is compiled and run. import java.util.*; class MyObject implements Cloneable { int i; MyObject(int ii) { i = ii; } public Object clone() { Object o = null; try { o = super.clone(); } catch(CloneNotSupportedException e) { System.err.println("MyObject can't clone"); } return o; } public String toString() { return Integer.toString(i); } } public class LocalCopy { static MyObject g(MyObject v) { v.i++; return v; } static MyObject f(MyObject v) { v = (MyObject)v.clone(); v.i++; return v; } public static void main(String[] args) { MyObject a = new MyObject(11); MyObject b = g(a); if(a == b) System.out.println("a == b"); else System.out.println("a != b"); System.out.println("a = " + a); System.out.println("b = " + b); MyObject c = new MyObject(47); MyObject d = f(c); 10 if(c == d) System.out.println("c == d"); else System.out.println("c != d"); System.out.println("c = " + c); System.out.println("d = " + d); } } Answer: a == b a = 12 b = 12 c != d c = 47 d = 48 11 Question 5 (10 marks): Complete the following code in the box, so that it will write the integers 0 through 9 to the output file “temp.test” in the text format. In next page, you can find the name of the functions you might use. import java.io.*; class Write { public static void main(String[] args) throws Exception { File file = new File("temp.test"); PrintWriter pw = new PrintWriter( new FileWriter(file)); for (int i=0;i<10;i++) pw.println(i); pw.close(); _______________________________________________________ _______________________________________________________ _______________________________________________________ _______________________________________________________ _______________________________________________________ } } 12 Classes, interfaces, and methods that you might need public class o public o public o public public class InputStreamReader extends Reader o An InputStreamReader is a bridge from byte streams to character streams public class FileWriter extends OutputStreamWriter o public FileWriter(File file) throws IOException public class PrintWriter extends Writer o public PrintWriter(OutputStream out) o o o BufferedReader extends Reader BufferedReader(Reader in) void close() throws IOException String readLine() throws IOException void println(Object x) Print an Object and then terminate the line. void println(String x) Print a String and then terminate the line. public void close()Close the stream. 13 Question 6. (15 marks) Comprehensive programming task: Don’t be afraid, the actual task is much easier than reading this long instruction. Imagine you’re a java programmer in a large shopping mall. Your boss, a technical manager, assigned you a task of maintaining customer information from all departments of the company. However, due to unnecessary data redundancy, one customer’s record may appear at different departments’ database, therefore, your first task is to remove all duplicate custom entries out of all entries that have been integrated from various departments. The data structure looks like this: class Customer { public int customerId; // primary key for a customer object protected String customerName; private InternalInformation customerInfo; // stores all other information for company's internal system usage public boolean equals(Object obj) { if( this.getClass() == obj.getClass() ) if( ((Customer)obj).customerId == this.customerId ) return true; return false; } } public class CustomerController { public Customer[] removeDuplicate( Customer[] customers ) {} } All you need to do is to implement the “removeDuplicate” method ( on page 17) in public class “CustomerController”, which takes in an array of Customer objects that have duplicates, i.e., some objects may have the same customerId, and outputs an array of Customer objects without any duplicates. Note, in case two or more objects represent the same customer, retain any one of them is okay. A naive algorithm you may come out with is “for each object, check all the others to see if there are any duplicates”. Unfortunately, this will result in a 2-layered nested for-loop and your boss will not accept it since he knows it’s definitely an O(n*n) algorithm. What you have to do is either 1) think over a “smart” algorithm that works better than O(n*n) or 2) use some java utility classes, especially in the realm of java Collection architecture, to disguise the time complexity so that your boss won’t find out the nested 2layered for-loop anymore and be satisfied with the result. You need only try either one of the two in this exam. 14 If you pick up the second choice, for your convenience, some of the class reference documents are listed below, all come from JDK1.3 documentation (not necessarily all of them will be used in your implementation): Some of the classes’ methods (shown with “*”) below will use Object’s “equals()” method to test if two objects are equal, so we have overridden “Object” class’s “equals()” method in “Customer” class as you can see. Therefore, you needn’t worry about how to test if two Customer objects are equal, they’re considered “equal” as long as they have the same “customerId” in our system. public class Vector extends AbstractList implements List, Cloneable, Serializable { public boolean add(Object element); //Appends the specified element to the end of this Vector *public boolean contains(Object elem); //Tests if the specified object is a component in this vector. public Object get(int index); //Returns the element at the specified position in this Vector. public int size(); //Returns the number of components in this vector. public void copyInto(Object[] anArray); //Copies the components of this vector into the specified array } public class HashSet extends AbstractSet implements Set, Cloneable, Serializable { *public boolean add(Object o); //Adds the specified element to this set if it is not already present. public boolean remove(Object o); //Removes the given element from this set if it is present. *public boolean contains(Object o); //Returns true if this set contains the specified element. public int size(); //Returns the number of elements in this set public Iterator iterator(); //Returns an iterator over the elements in this set } public class HashMap extends AbstractMap implements Map, Cloneable, Serializable { *public Object put(Object key, Object value); //Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced. public Object get(Object key); //Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key public int size(); //Returns the number of key-value mappings in this map *public boolean containsKey(Object key); //Returns true if this map contains a mapping for the specified key public Collection values(); //Returns a collection view of the values contained in this map } public interface Collection { public Iterator iterator(); //Returns an iterator over the elements in this collection public Object[] toArray(); //Returns an array containing all of the elements in this collection public int size(); //Returns the number of elements in this collection } public interface Iterator { public Object next(); //Returns the next element in the interation. public boolean hasNext(); //Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.) } 15 public Customer[] removeDuplicate( Customer[] customers ) { Vector info = new Vector(customers.length); for (int i = 1; i<=customers.length; i++) { if (! info.contains(customers[i])) info.add(customers[i]); } //check existence //add to vector int size = info.size(); //get size Customers[] temp = new Customers[size]; info.copyInto(temp); Return temp; } 16