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
CIS 121 – Problem-solving and Programming Concepts II Practice Test III This practice test is intended to provide examples of questions that may be asked on the final exam covering only the material covered since Exam II. Please also refer back to Practice Test I and Practice Test II to thoroughly review the material that will be covered on the Final Exam. Of course, as in past examinations, you are responsible for attending class regularly and completing all reading and program/lab assignments to fully prepare for examinations. Homework: Write two test questions for the final exam. The questions, to be considered for the final exam, must accurately reflect the proportion of the course devoted to the objective and be reasonable in complexity for a student completing the CIS121 course. Question 1: Objective-- Demonstrate a concept covered in Chapters 9 through 13. Question 2: Objective—Demonstrate understanding of concurrent programming, files or linked lists. Part One: Fill-in-the-blank 1) Streams provide communication channels between a program and a specific device or file 2) In order to write objects to a file using ObjectOutputStream, the Serializable interface must be implemented. 3) A queue is a FIFO data structure of data items. 4) The primary operations performed on a Stack are pop and push. 5) A class that contains a data member that refers to a class object of the same class is said to be a self-referential class. 6) An object that can hold other objects is known as a container 7) According to the Data Hierarchy, a file is a group of related records. 8) RandomAccess files are used for applications where “Instant Access” to the data is needed, such as an ATM machine. 9) Because lists are structures that can grow and shrink at execution time they are called dynamic data structures. 10) A key field is one that identifies a record as unique from all other records. 11) In a concurrent programming environment, waiting can be dangerous. It can lead to two serious problems called deadlock and starvation (Be prepared to also define each) 12) Every Java thread has a priority in the range of MIN_PRIORITY to MAX_PRIORITY with an int value of 1 to 10 The default priority is NORM_PRIORITY with an int value of 5. 13) One programming solution to the problem of a producer thread producing more than a consumer thread can consume is to implement what data structure? circular buffer 14) Ultimately, all data items processed by a computer are reduced to combinations of 0 and 1. 15) Method close( ) of the file stream classes FileOutputStream, FileInputStream and RandomAccessFile closes a file. 16) RandomAccessFile method readInt( ) reads an integer from the specified stream. 17) RandomAccessFile method readLine( ) reads a line of text from the specified stream. 18) RandomAccessFile method seek( ) sets the file-position pointer to a specific location in a file for input or output. That position, also referred to as the record offset, is computed. For example if I wanted to position the file pointer to read the fourth record, the formula for computing the offset would be record # * size of record. Part II: Short Answer and Discussion. 19) List and briefly describe each level of the “data hierarchy.” bit – 0 or 1 – byte – a group of meaningful bits - character – unicode – ASCII – 8 bits or 16 bits field - a group of meaningful bytes – such as a “name” record – a group of related fields – in java an instance of a class file – a group of related records database – a group of related files 20) What are the states of a thread and the state transitions of each. P. 738 constructor call BORN start( ) READY quantum expires or yeild( ) dispatched by OS RUNNING wait( ) notify( ) WAITING sleep( ) interval expires SLEEPING I/O request complete DEAD I/O complete BLOCKED 21) Explain the steps necessary to write to a sequential file using ObjectOutputStream. See readWriteObjects.java (shared drive) 1) Declare a variable of type ObjectOutputStream (OOS) 2) Open the file by chaining the OOS variable to a file OutputStream object (initialized with fileNname) 3) Write objects to file using the OOS Variable until all objects are written. 4) Close file (flushes buffer and closes file). 22) Explain the steps necessary to write to a random access file using RandomAccessFile. Explain the requirements of reading and writing data with the intention of accessing a single record within a file. What are the “mechanics” for success? See File I/O lab (shared drive) and text book 1) Declare a RandomAccessFile(RAF) variable 2) Open file by constructing an RAF object with filename as parameter 3) Position pointer for reading/writing selected record (seek( )) 4) Read or write from/to file 5) Close file. Requirements: Class must have additional methods to ensure constant size for reading/writing (fixed-length records). Mechanics require that you move the file position pointer to the point of insert or extraction with each direct access to file. 22) Compare and contrast linked lists versus arrays (pros, cons, complexity of representative operations). Array vs Linked-List Attribute Size Array Fixed at time of array allocation Ex: myInts = new int[20]; Linked List Can grow. Limited only by available heap space. Space efficiency Good! No wasted space to hold a pointer to the next item in the list. Array contents are stored contiguously. For example in an array of 10 ints those ints are stored back to back. Nodes that are linked by the linked list are themselves all allocated on the heap. Each node needs a “next” node reference in it and possibly a “previous” node reference if it is to be doubly linked. Traversal Location of each item is computed as an Each node in list holds the address of the offset from start of array space, therefore is next node hence we use ‘pointer’ fairly fast. extraction from a node to walk to next node. Ease of adding item Not good! We must write code to move all Good! We just adjust two node items from given location down one to references to insert the new node into make space for new item. the list. Ease of deleting Not good! We must move all items after Good! We need only to adjust one node the given location up one space to close the reference to bypass node to be deleted. hole after a deletion. Garbage collector helps too. Searching:unsorted Linear search Searching:sorted Binary search complexity! Linear search possible! O(log2N) Linear search needed O(N) complexity. 23) Explain in order the steps needed to place a new data element in a sorted linked list, assume duplicates are allowed. 1) Find the insertion point in existing list, special cases of empty list and prior to first. (Walker points to node to precede the new node after insertion in non-special case scenario) 2) If empty or prior to first, set the new node’s next reference to reference the “old” first (null or address of an exiting node) and set first to reference the new node. 3) Else, Set new node’s next reference to walker’s next and walker’s next to the new node. 24) Why should list class definitions contain methods that are synchronized? Classes should be as complete and general as possible. If the list is a shared data location when using threads, the objects accessing the methods of the class must act as monitors to protect the integrity of the shared data, allowing access to only one object at a time. 25) Describe the 3 elements that make up a well-written recursive method. 1) A stopping point 2) With each recursive call, problem set is reduced; therefore getting closer to the stopping point each call. 3) The method calls itself 26) Match the following list methods and instance variables to the appropriate stack/queue methods and instance variables (note: some letters may appear in more than one answer). __d___ dequeue a. insertAtBack h. medianNode __b___ push b. insertAtFront i. lastNode __a___ enqueue c. insertSorted __d___ pop d. removeFromFront __g___ head e. removeFromBack __g___ top f. removeMedian __i___ tail g. firstNode Part III: Programming. 1) Fill in the constructor for the class LowThread below: // Program demonstrates high priority threads import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Demo extends JFrame { private HighThread high; private LowThread low; private JTextArea output; public Demo() { super( "Demo" ); output = new JTextArea( 10, 20 ); getContentPane().add( output ); setSize( 250, 200 ); setVisible( true ); low = new LowThread( output ); low.start(); high = new HighThread( output ); high.start(); } public static void main( String args[] ) { Demo app = new Demo(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } class HighThread extends Thread { private JTextArea display; public HighThread( JTextArea a ) { display = a; setPriority( Thread.MAX_PRIORITY ); } public void run() { for ( int x = 1; x <= 5; x++ ) display.append( "High Priority Thread!!!\n" ); } } class LowThread extends Thread { private JTextArea display; public LowThread( JTextArea a ) {//what lines of code minimally go here? display = a; setPriority( Thread.MIN_PRIORITY ); } public void run() { for ( int y = 1; y <= 5; y++ ) display.append( "Low Priority Thread!!!\n" ); } } 2) Fill in the blanks for the following methods: public void writeRecord( PineTreeData record ) { // Writes record as an object. try { outputFile.writeObject (record) // Write record. outputFile.flush ( )_______________________; } catch ( IOException io ) { JOptionPane.showMessageDialog( this, "Error adding record", "Error", JOptionPane.ERROR_MESSAGE ); close OutputFile ( ); } } private void closeInputFile( ) { try { inputFile.close( ); } catch ( IOException e ) { JOptionPane.showMessageDialog( this, "Error closing input file", "Error", JOptionPane.ERROR_MESSAGE ); System.exit(1); } } 3) Assume that each of the following statements applies to the same program. a. Write a statement that opens file “oldmast.dat” for input; use ObjectInputStream object inOldMaster chained to a FileInputStream object. ObjectInputStream inOldMaster; inOldMaster = new ObjectInputStream (new FileInputStream (“oldMast.dat”)); b. Write a statement that opens file “newmast.dat” for output (and creation); use ObjectOutputStream object outNewMaster chained to a FileOutputStream. ObjectOutputStream outNewMaster; outNewMaster = new ObjectOutputStream (new FileOutputStream (“newmast.dat”)); c. Write a set of statements that reads BankAccount objects sequentially from the file “oldMast.dat” into an array of BankAccounts, accounts, for update processing. //Assume Accounts and other variables have been defined int i = 0; try { while (true) //exit with end of file exception account [i] = (BankAccount) inOldMaster.readObject( ) ; i++; } catch (EOFException eof) { try { inOldMaster.close(); } catch(IOException ioe) { System.exit(1); } } d. Write a set of statements that writes the updated accounts array to the “newmast.dat” file. try { for (int i = 0; i < totalAccounts; i ++) outNewMaster.writeObject(accounts[i]); } catch(IOException ioe) { System.exit(1); } finally { try { outNewMaster.close(); } catch(IOException ioe) { System.exit(1); } } 4) ListNode class has the following instance variables: Object o; ListNode next; a) Write the insertAtBack method for a a singly linked list of listNodes. See List class example in book (22.3) b) Write the insertAtFront method for the same list described in a. See List class example in book (22.3) c) Write the toString method for the list described in a. See examples in book 5) Write a program that creates a link list object of 10 characters, then creates a second list object containing a copy of the first list but in reverse order. Below is one simple solution of several possible: //appropriate import statements //LinkList class with list methods defined public class PracticeFinal { public static void main(String[] args)throws IOException { LinkList myList = new LinkList(); for (char i = 'a'; i <= 'j'; i ++) myList.addToFront(new Character(i)); System.out.println(myList); LinkList reverseList = new LinkList(); //now copy to second list for (int i = 1; i <= 10; i++) reverseList.addToFront(myList.removeFromFront()); System.out.println(reverseList.toString()); } }