CS365 Midterm -- Spring 2017

  1. This exam is closed-note, closed-book.
  2. You must answer all of the questions.
  3. Answer the questions on the exam itself and hand in the exam.
  4. Good luck!

  1. (11 points: General) For each question below, look at the following list of items and fill in the blank with the best choice.
    package       extends      import            virtual method
    interface     type         namespace         replicated inheritance
    class         finally      final             multiple inheritance
    public        Scanner      const             shared inheritance
    protected     subclasses   static            polymorphism
    composition   inheritance  iterator          friend
    Error         Throwable    Exception         RuntimeException
    packagepath   events       interrupts        non-virtual method
    implements    classpath    include           filepath
    import        signals      throw             reference counting
    void *        void         type erasure      generational collector
    importpath    includepath  catch             non-virtual method
    catch         try          try               pure virtual method
    
    1. ________________ This type of method cannot be overridden by its subclasses. In other words, the subclasses must accept its implementation.

    2. ________________ The super type for all C++ pointers.

    3. ________________ The technique I can use in Java to inherit a class's implementation but not its interface. The technique stores an instance of the class and delegates implementation to the class's methods.

    4. ________________ The technique that Java uses to convert template code into a compileable piece of code. The technique involves replacing each template parameter with its upper bound object.

    5. ________________ The name of the flag passed to either the java compiler or virtual machine that allows it to locate the directories where packages might be stored.

    6. ________________ A concept that refers to a procedure that performs the same type of action on different types of data.

    7. ________________ In graphical user interfaces, input arrives via this mechanism.

    8. ________________ A type is a set of values + a set of operations on those values. In Java, you declare a type using this keyword.

    9. ________________ The Java super class for all exceptions that are considered catastrophic (e.g., out of heap memory) and should be caught by the virtual machine

    10. ________________ The mechanism used by C and C++ to announce unrecoverable errors, such as segmentation faults or bus errors

    11. ________________ The keyword you use in C++ to declare that a class will be allowed to access another class's protected and private members.

  2. (10 points: Event Handling) For each question below, look at the following list of items and fill in the blank with the best choice(s).
    BorderLayout               BoxLayout             GridLayout
    FlowLayout                 text box              slider
    radio buttons              check boxes           command buttons
    JFrame                     JPanel                JComponent
    menu                       ComboBox              JContainer
    Glue                       RigidArea             Strut
    

    1. ____________________ The type of object I can insert between two components being laid out using a horizontal Box Layout manager to force the first component to stay attached to the left side of the window and the second component to stay attached to the right side of the window when the window is resized.

    2. ____________________ The type of layout manager I should use for a pallette of tools or color chips, where each element should be the same size.

    3. ____________________ The type of widget to use when I have 5-7, mutually exclusive items I wish a user to select.

    4. ____________________ The type of layout manager to use when I want to have a central drawing canvas and tool pallettes around the sides of the canvas.

    5. ____________________ The type of widget to use when I want the user to select the US state or territory in which they live and I want to give the user the option of either typing in their choice or selecting it from a set of choices.


    For each of the following questions circle the best response. Each question in this section is worth 4 points.

  3. Suppose you have a pre-existing Java class named ListNode that has an integer variable named value and a pointer to the next list node named next. How should you declare a subclass of ListNode named DNode that adds a second pointer to the previous list node named prev?

    1. class DNode extends ListNode {
        int value;
        ListNode next;
        ListNode prev;
      }
      	  
    2. class DNode : public ListNode {
        ListNode *prev;
      }
      		  
    3. class DNode extends ListNode {
        ListNode prev;
      }
      	  
    4. class DNode extends ListNode {
        ListNode *prev;
      }
      		  

  4. Which of the following Java code fragments declares and creates an array of 10 Strings?

    1. String names[] = new String[10];
    2. String names[10];
    3. String names[](10);
    4. names<Strings>[] = new String[10];

  5. Assume that you have declared a Java class named TreeNode as follows:
    class TreeNode {
      public int value;
      public TreeNode leftChild;
      public TreeNode rightChild;
    }
          
    Also assume you have declared and initialized two variables named subtree1 and subtree2 of type TreeNode. Which of the following code fragments declares a variable named root of type TreeNode, assigns it a new TreeNode, assigns it a value of 10, and makes the leftChild field point to subtree1 and the rightChild field point to subtree2?

    1. TreeNode root;
      root.value = 10;
      root.leftChild = subtree1;
      root.rightChild = subtree2;
      	     
    2. TreeNode *root = new TreeNode();
      root->value = 10;
      root->leftChild = subtree1;
      root->rightChild = subtree2;
      	     
    3. TreeNode root = new TreeNode();
      root->value = 10;
      root->leftChild = subtree1;
      root->rightChild = subtree2;
      	     
    4. TreeNode root = new TreeNode();
      root.value = 10;
      root.leftChild = subtree1;
      root.rightChild = subtree2;
      	     
  6. Which of the following code fragments correctly declares a generic Java class named Pair that has:

    1. template <class K, class V>
      class Pair {
        K key;
        V value;
        public Pair(K k, V v) {
          key = k;
          value = v;
        }
      }
      		
    2. class Pair<K, V> {
        K key;
        V value;
        public Pair(K k, V v) {
          key = k;
          value = v;
        }
      }
      		
    3. class<K, V> Pair {
        K key;
        V value;
        public Pair<K, V>(K k, V v) {
          key = k;
          value = v;
        }
      }
      		
    4. class Pair {
        K key;
        V value;
        public Pair(K k, V v) {
          key = k;
          value = v;
        }
      }
      		

  7. Why is the following C++ constructor with an initialization list preferable to the following C++ constructor without an initialization list?

    Foo(string s) : name(s) {} // with initialization list
           

    Foo(string s) { // without initialization list
       name = s;
    }
           

    1. The constructor with the initialization list allocates objects from the stack while the constructor without the initialization list allocates objects from the heap which the programmer must later manually de-allocate.
    2. The constructor with the initialization list works even if the argument that is passed to the constructor is a char * whereas the constructor without the initialization list works only if the argument that is passed to the constructor is a string.
    3. The constructor with the initialization list is the only way that you can assign stack-allocated objects to variables declared as stack-allocated objects
    4. The constructor with the initialization list only calls the string copy constructor while the constructor without the initialization list calls both the 0-argument default string constructor and the string assignment operator.

  8. In object-oriented programming, what does inheritance allow?

    1. It allows one class, the subclass, to be based on another class, the superclass, and allows the subclass to either use the same implementation or to specify a new implementation to maintain the same behavior
    2. It allows one class to base its implementation on the implementation of another class without also having to accept that class's API (application programmer interface).
    3. It allows a group of cooperating classes to implement an algorithm or data structure, such as a linked list or tree, by mutually sharing their implementation, while protecting their implementation from the outside world.
    4. It allows a programmmer to specify the operations that will be permitted on a type without requiring the programmer to provide an implementation for those operations.

  9. What danger is associated with the setjmp/longjmp commands in C?

    1. Destructors will not be executed for any stack-allocated objects held in stack frames that are thrown away by the longjmp command.
    2. It will not be possible to determine what type of exception caused the longjmp command to execute.
    3. Any values that were held in registers by the protected code and not written to memory are lost.
    4. The memory allocator will not be able to reclaim the memory of any stack-allocated objects in the stack frames that are thrown away and hence the program will have a memory leak.

  10. The following type of garbage collector performs 3 steps: 1) walk through the heap and mark every block as "useless", 2) for each pointer outside the heap do a depth-first search and mark all blocks that are encountered as "useful.", and 3) walk through the heap again and move every block still marked as "useless" to the free list.
    1. reference counting
    2. mark-sweep
    3. stop-and-copy
    4. generational collectors

  11. Suppose you have the following four classes that implement a map type that supports the operations find, insert, and delete: In addition the three tree classes provide an additional getKeys operation that returns an array of keys in sorted order.

    If you forget from CS140 and CS302, Red Black trees and AVL trees are balanced binary search trees. They implement exactly the same find and getKeys operations as binary search trees and implement different insert and delete operations that rebalance the trees.

    Based on what you were told in class, select the best Java inheritance hierarchy to represent this map types and its implementing classes:

    	    (a)
                Map
    	(interface)
    	    |
       -------------------
       |                 |	    
    HashTable      BinarySearchTree
     (class)          (class)
    		/         \
    	  RedBlackTree   AVLTree
    	    (class)      (class)
    	    
    	  
    	    (b)
                Map
    	  (class)
    	    |
       -------------------
       |                 |	    
    HashTable      BinarySearchTree
     (class)          (class)
    		/         \
    	  RedBlackTree   AVLTree
    	    (class)      (class)
    	    
    		  
    	    (c)
                Map
    	(interface)
    	     |
       --------------------------------------------------
       |                 |	               |            |
    HashTable      BinarySearchTree    RedBlackTree   AVLTree
     (class)          (class) 	     (class)      (class)
    	    
    	  
    	    (d)
               Map
    	 (class)
    	    |
       --------------------------------------------------
       |                 |	               |            |
    HashTable      BinarySearchTree    RedBlackTree   AVLTree
     (class)          (class) 	     (class)      (class)
    	    
    	  
    	   (e)
               Map
    	(interface)
    	    |
       -------------------
       |                 |	 
    HashTable          Tree
    (class)          (class)
                         |	    
                -------------------------------
                |                |            |
        BinarySearchTree    RedBlackTree   AVLTree
             (class)           (class)     (class)
    	    
    	  
    	   (f)
               Map
    	 (class)
    	    |
       -------------------
       |                 |	 
    HashTable          Tree
    (class)          (class)
                         |	    
                -------------------------------
                |                |            |
        BinarySearchTree    RedBlackTree   AVLTree
             (class)           (class)     (class)
    	    
    	 

  12. You are given the following Java class declarations:
    class RecognitionError extends Exception { ... }
    class MismatchedTokenError extends RecognitionError { ... }
    class InvalidTokenError extends RecognitionError { ... }
    class NoAvailableAlternativeError extends RecognitionError { ... }
    class MismatchedNumberError extends MismatchedTokenError { ... }
    class MismatchedOperatorError extends MismatchedTokenError { ... }
    	  
    and the following code:
    try {
      throw new InvalidTokenError();
    }
    catch(RecognitionError e) { ... }
    catch(MismatchedTokenError e) { ... }
    catch(InvalidTokenError e) { ... }
    catch(Exception e) { ... }
    	  
    Which catch statement will catch the exception thrown in the try block?

    1. catch(RecognitionError e) { ... }
    2. catch(MismatchedTokenError e) { ... }
    3. catch(InvalidTokenError e) { ... }
    4. catch(Exception e) { ... }


    For the following questions circle all answers that apply.

    • You will get one point for each correct answer
    • Each problem indicates how many points its worth and its point value indicates how many correct answers there are. Only circle that many answers.
    • If you circle more answers than the problem is worth, you will lose one point for each additional answer.

  13. (4 points) Suppose you have the following Java interfaces and classes:
    interface Stack { ... }
    interface Serializable { ... }
    class AbstractStack implements Stack, Serializable { ... }
    class StackList extends AbstractStack { ... }
    class StackDoubleLinkList extends StackList { ... }
         
    Further assume that AbstractStack is an abstract class that has one or more pure virtual methods. Circle all of the following declaration that are legal:

    1. Stack myStack = new AbstrackStack();
    2. Stack myStack = new StackList();
    3. Serializable myStack = new StackDoubleLinkList();
    4. Serializable myStack = new StackList(); Stack s = myStack;
    5. AbstractStack myStack = new AbstractStack();
    6. AbstractStack myStack = new StackList();
    7. AbstractStack myStack = new StackDoubleLinkList();
    8. StackDoubleLinkList myStack = new StackList();
    9. StackDoubleLinkList myStack = new Serializable();

  14. ( 3 points) Which of the following reasons helps explain why Java programs run more slowly than C++ programs.

    1. Java byte codes are often interpreted by the Java VM while C++ programs are compiled into and run as machine instructions.
    2. Java methods are always virtual and hence require a runtime lookup through a vtable in order to be executed whereas C++ methods can always be statically compiled and hence can be executed via a simple jump instruction.
    3. The Java virtual machine provides various runtime services, such as garbage collection and array bounds checking, that slow down the execution of a program.
    4. All values in Java, whether they are primitive types or instances of objects, must be allocated off the heap rather than being stack-allocated.
    5. Just in time compilers can compile byte codes into machine instructions but C++ compilers can achieve better optimizations by looking at the original source code.
    6. Java only allows arguments to be passed by value which means that large objects have to be copied to and from functions, resulting in greater memory allocation and management.

  15. (3 points) What disadvantages are associated with reference counting garbage collectors?

    1. can cause long annoying pauses when garbage collection occurs.
    2. cannot garbage collect circular structures.
    3. only allows half of virtual memory to be used at one time.
    4. requires that the language be strongly typed.
    5. requires counting statements to be placed before and after every pointer assignment.
    6. is much more complicated to implement than "tracing" collectors, like mark-sweep or stop-and-copy.


  16. (8 points) Suppose you have the following set of Java class declarations
    package foo;
    
    class A {
      int x;
      protected int y;
    }
    
    class B { ... }
    
    package goo;
    
    class C extends A { ... }
    
    class D { ... }
    	
    Just to be clear, classes A and B are in package foo and classes C and D are in package goo. In the following table, place an X in each box in which member functions of that class may access the indicated variable (i.e., you are using the X's to indicate the classes in which x and y are visible).

    classxy
    A  
    B  
    C  
    D  

  17. (6 points) Consider the following Java code:
    class fruit {
      public void printType() {
        System.out.printf("fruit%n");
      }
    
      public static void main(String args[]) {  // code in main to keep it simple
        fruit f = new orange();
        f.printType();
        f = new apple();
        f.printType();
      }
    };
    
    class orange extends fruit {
      public void printType() {
        System.out.printf("orange%n");
      }
    };
    
    class apple extends fruit {};
    
    What is the output of fruit's main method?

    The following questions refer to the following piece of code:

    package adder;
    import java.util.Scanner;
    
    class SumList {
        class NegativeNumberError extends Exception { 
    	int value;
             public NegativeNumberError(int i) {
               value = i;
             }
             int getNumber() { return value; }
        }
        class BadNumberError extends Exception {
    	String value;
    	public BadNumberError(String v) {
    	    value = v;
    	}
    	String getValue() { return value; }
        }
        
        void printSum(String line) throws BadNumberError, NegativeNumberError {
    	int x;
    	int sum = 0;
    	Scanner lineTokenizer = null;
    	try {
    	    lineTokenizer = new Scanner(line);
    	    while (lineTokenizer.hasNext()) {
    		x = lineTokenizer.nextInt();
    		if (x < 0) throw new NegativeNumberError(x);
    		sum += x;
               }
    	}
    	catch(java.util.InputMismatchException e) {
    	    throw new BadNumberError(lineTokenizer.next());
    	}
    	finally {
    	    System.out.printf("sum = %d%n", sum);
    	}
        }
    
        SumList() {
    	Scanner console = new Scanner(System.in);
    	int lineCount = 1;
    	while (console.hasNextLine()) {
    	    try {
    		printSum(console.nextLine());
    	    }
    	    catch (NegativeNumberError ne) {
    		System.out.printf("Negative number %d on line %d%n",
    				  ne.getNumber(), lineCount);
    	    }
    	    catch (BadNumberError be) {
    		System.out.printf("Value %s is not a number on line %d%n",
    				  be.getValue(), lineCount);
    	    }
    	    finally {
    		lineCount++;
    	    }
    	}
    	console.close();
        }
    	    
        public static void main(String args[]) {
    	new SumList();
        }
    }
    
  18. (10 points) Suppose that the input to this program is:
    3 10 4
    3 brad
    7 4 9 3
    8 6 10 -2 -4
    17 -3 nancy
        
    What is the output of this program?
    
    
    
    
    
    
    
          
    
    
    
    
    
    
    
    
    
        
  19. (4 points) The finally clause in printSum should have an additional statement in it. What should that statement be?

    1. System.exit(0);
    2. lineTokenizer.close();
    3. return sum;
    4. lineTokenizer.readToEndOfLine();

  20. (5 points) Assume that SumList is stored in the directory /home/bvz/cs365/adder. Write the java command that should be used to execute the java virtual machine on SumList, regardless of what directory you are in when you execute the command.