CS365 Midterm -- Spring 2015

  1. You may use a one page front-and-back "cheat" sheet for this exam. You may not use a computer or any electronic devices.
  2. You must answer all of the questions.
  3. Answer all the questions on the exam itself and hand in the exam.
  4. You must use Java to implement the coding question.
  5. Good luck!

  1. (14 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         Console      final             multiple inheritance
    public        Scanner      const             shared inheritance
    protected     subclasses   static            polymorphism
    composition   inheritance  iterator          abstract class
    friend
    

    1. ________________ A set of values + a set of operations that manipulate those values

    2. ________________ If you are writing a class in C++, the keyword you would use to indicate that another class is allowed to use your class's protected variables.

    3. ________________ The Java construct used to declare an abstract type.

    4. ________________ If I want a square to inherit a rectangle's implementation, but not its interface, I can do so by making the square contain a pointer to a rectangle object and delegating any behavior I wish to inherit from the rectangle by calling the appropriate methods in the rectangle. What is the name of this technique?

    5. ________________ Suppose I want class D to multiply inherit from two superclasses, B and C, and that B and C both inherit from A. If I want D to contain only one copy of A, what type of inheritance do I want?

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

    7. ________________ The keyword used in Java to declare the module to which a class belongs.

  2. (10 points: General) Answer true or false for the following questions.

    1. ________________ Event driven programming differs from procedural programming in that the user, rather than the program, controls what type of input is processed next by the program.

    2. ________________ A subtype is allowed to implement only a proper subset of a type's operations.

    3. ________________ In Java, methods are virtual by default.

    4. ________________ Instance variables that are declared as protected can be accessed by any class within the same package.

    5. ________________ It is permissable to create objects that are instances of an abstract class (i.e., you can call the new operator with an abstract class).

  3. (12 points: Generics) Answer the following questions about C, C++, and Java's generics/template mechanisms:

    1. ________________ The language(s) whose generics mechanism allows generics to be instantiated with primitive types, such as int or double.

    2. ________________ The language(s) that allow their generic code to be compiled, since only one copy of the code is required.

    3. ________________ The term used for Java's ability to store primitive types in a generic by automatically converting them to an object of the appropriate type, and on retrieval from the generic, automatically converting them back to the appropriate primitive type.

    4. ________________ The language(s) that allow the programmer to specify that the type used to instantiate a generic should support a certain API.

    5. If I want to create a generic Box struct in C that stores a single value, how should I declare it? Circle the best answer.
      1. struct Box {
            generic value;
        };
        
      2. struct Box<T>
            T value;
        }
        
      3. struct Box {
            void *value;
        };
        
      4. struct Box {
            void value;
        }
        

  4. (10 points: Inheritance) Answer the following questions about inheritance. For the multiple choice problems circle the best answer.

    1. This type of polymorphism occurs with inheritance hierarchies and allows subclasses to define different implementations for the same method, with the intention that the different method implementations all achieve the same outcome (e.g., draw an object)
      1. parametric polymorphism
      2. generic polymorphism
      3. subtype polymorphism
      4. inheritance polymorphism

    2. How would I declare a pure virtual method in Java?
      1. abstract void draw();
      2. virtual void draw() = 0;
      3. virtual void draw();
      4. void draw() = 0;

    3. What is the output of f.type() and a.type in the following, abbreviated, Java program:
      
      f.type(): __________________________
      
      a.type(): __________________________
      
      class fruit {
          void type() { System.out.println("fruit"); }
      
          public static void main(String[] args) {
                fruit f = new apple();
                apple a = new apple();
                f.type();
                a.type();
          }
      }
      
      class apple extends fruit {
          void type() { System.out.println("apple"); }
      }
      
    4. In C++, if I want the subclass Circle to inherit Oval's implementation but not its interface, how should I declare Circle?

      1. class Circle : public Oval { ... };
      2. class Circle extends protected Oval { ... };
      3. class Circle : protected Oval { ... };
      4. class Circle : protected super Oval { ... };
      5. class Circle : protected base Oval { ... };
      6. class Circle : implementation Oval { ... };

    5. Virtual methods are implemented by:
      1. Inlining their method body in the calling procedure
      2. Using a vtable to find the address of the appropriate method body and then jumping to that address to execute the method body.
      3. Following a chain of superclass pointers from the leaf until you find a class object that contains a method with the appropriate name and executing that method's function body.
      4. Searching from the root of the inheritance hierarchy toward the leaf until you find a class object that contains a method with the appropriate name and executing that method's function body.

  5. (13 points: Exception Handling) Answer the following questions about exception handling in C, C++, and Java by circling the best answer.

    1. In C++, suppose I want to throw an array out of bounds exception and I want to pass the subscript as an argument. What is the best way to make the throw?
      1. throw index;

        where index is the integer index that is out-of-range.

      2. throw ArrayOutOfBoundsException(index);

        where ArrayOutOfBoundsException is a class that can store the out-of-bounds index and index is the out-of-bounds index.

      3. throw new ArrayOutOfBoundsException(index);

        where ArrayOutOfBoundsException is a class that can store the out-of-bounds index and index is the out-of-bounds index.

      4. throw exception(index);

        where index is the integer index that is out-of-range.

    2. In C++, I have the following class declarations:
          class StackException;
          class StackLogicException : public StackException;
          class StackRuntimeException : public StackException;
          class StackEmptyException : public StackRuntimeException;
          class StackLengthException : public StackLogic Exception;
      
      and the following throw statement:
          throw StackLengthException();
      
      Which of the following catch clauses can catch this exception? Circle all that apply.
      1. catch (StackException)
      2. catch (StackLogicException)
      3. catch (StackRuntimeException)
      4. catch (StackEmptyException)
      5. catch (StackLengthException)
      6. catch (StackLengthException *)
      7. catch(std::exception)
      8. catch(...)
      9. catch(default)
      10. catch(StackLengthException &)

    3. Suppose you have the following general construction in Java:
      ... assign some value to x ...
      try {
         if (x < 10)
              throw new Exception();
      }
      catch ...
      catch ...
      finally { ... }
      
      Under what conditions would the finally clause execute? Circle all conditions that apply.
      1. When the try block completes successfully without throwing the Exception object
      2. When the try block throws the Exception object and one of the catch clauses catches and handles it
      3. When the try block throws the Exception object, one of the catch clauses catches and handles it, and then rethrows it.
      4. When the try block throws the Exception object up the call chain because none of the catch clauses handle it.

    4. What is the pre-defined Java base class for creating programmer-defined exceptions that will be checked by the compiler (i.e., the compiler will require the throwing function to either handle the exception or declare that it is throwing it out of the function)?
      1. Error
      2. Exception
      3. Throwable
      4. RuntimeException

  6. (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                 GridBagLayout         text box              
    slider                     menu                  command buttons
    radio buttons              check boxes           content pane
    JFrame                     JPanel                JComponent
    Adapters                   Listeners             Delegators
    Command Objects            Generators            JContainer
    

    1. ____________________ The type of widget I should use to allow a user to enter a 5 digit zip code.

    2. ____________________ The layout manager that allows a programmer to position objects either vertical or horizontally and that allows the user to use invisible "spacer" objects, such as glue objects and rigid area objects, to control the spacing of objects.

    3. ____________________ The layout manager that I might use to layout a dialog box that is roughly organized as a grid but which requires different row and column sizes, and which also requires some widget groups to span multiple rows or columns.

    4. ____________________ The general name given to the Java objects which are added to widgets in order to be notified of and to handle events generated by these widgets.

    5. ____________________ The widget you should use to allow a user to select any of the following 6 toppings for their burrito: cheese, onions, olives, guacamole, sour cream, salsa. The user is allowed to select as many of these toppings as they wish (i.e., they are not mutually exclusive).

  7. (10 points): Object-Oriented Programming Your manager has asked you to take over a botched Java project in which three different programmers produced three different classes to handle a menu widget for the Mac, Windows, and X window systems. The problem is that each programmer created an inheritance hierarchy for their window system, so the MacMenu class inherits from Mac, the WindowsMenu class inherits from Windows, and the XMenu class inherits from X. At least enough process control was exercised so that the Mac, Windows, and X programmers all chose getChoice as their method for accessing the currently selected menu item. Your product is about to ship and it is supposed to support all three platforms but you do not want your users to worry about what type of menu they have created after the initial creation of the menu. You want the user to be able to say something like:

      
    Menu FileMenu = (winSystem == MAC ? new MacMenu : 
                    (winSystem == WINDOWS ? new WindowsMenu : 
                                            new XMenu));
    ...
    String selection = FileMenu.getChoice();
    

    Right now the user will not be able to do that. Instead the user will have to write code that looks like:

    MacMenu = (winSystem == MAC ? new MacMenu : null);
    WindowsMenu = (winSystem == WINDOWS ? new WindowsMenu : null);
    XMenu = (winSystem == X ? new XMenu : null);
      ...
    String selection = (winSystem == MAC) ? MacMenu.getChoice()
                : ((winSystem == WINDOWS) ? WindowsMenu.getChoice();
                : XMenu.getChoice());
    
    How can you arrange to quickly correct this problem and allow the product to ship on time? You are not allowed to changed the inheritance hierarchy because that would be too time-consuming. Clearly you must declare a new data type called Menu and you will have to modify the three classes. Show the class/interface declarations that you must write or modify. You should not show any more than what must be modified or added and you do should not modify or add any executable code.

  8. (3 points: Executing a Java Program) Read the description for question 9 and then answer this question. Assume that: Write the full java command required to execute the PrintScores program that you will write in question 9..
    
    
    
    
  9. (18 points): Java Programming Write a public Java class called PrintScores that meets the following specifications:

    1. The class should be part of the package bvz.
    2. It should use the technique I showed you in which the constructor is used to implement whatever you would normally implement in main.
    3. Your program should read scores and student names from a grade file that has been redirected to stdin, and for each student it should print the student's maximum score. The grade file lists a student's scores and then the student's name. The grade file may have multiple students. For example:
      89
      75
      93
      53
      BabyDaisy
      86
      45
      100
      Smiley
      
      Your program should read student scores from stdin, and output the student's name and the student's maximum score. For example, for the above file your program should output:
      BabyDaisy 93
      Smiley 100
      
    4. You are guaranteed that:
      • there is at least one score for each student,
      • that all scores are greater than 0,
      • that all scores are integers, and
      • that every set of scores ends with a one word name.
    5. You must use format to create your output.
    6. The API for the Scanner class has been provided at the end of this exam.
    Write your answer on the next page.
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

Scanner API

This API includes more methods than I used in my solution, but I do not want to give away the solution, nor do I want to limit you in what you use. Conversely, if you find that you want to use a method not in this list, then you are almost certainly on the wrong track.

Constructors

ConstructorDescription
Scanner(InputStream source)Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(String source) Constructs a new Scanner that produces values scanned from the specified string.

Methods

MethodDescriptionThrows
void close() Closes this scanner. ---
boolean hasNext() Returns true if this scanner has another token in its input. ---
boolean hasNextBoolean() Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false". ---
boolean hasNextDouble() Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. ---
boolean hasNextInt() Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. ---
boolean hasNextLine() Returns true if there is another line in the input of this scanner. ---
string next() Finds and returns the next complete token from this scanner. NoSuchElementException - if no more tokens are available
boolean nextBoolean() Scans the next token of the input into a boolean value and returns that value. InputMismatchException - if the next token is not a valid boolean
NoSuchElementException - if input is exhausted
double nextDouble() Scans the next token of the input as a double. InputMismatchException - if the next token is not a valid boolean
NoSuchElementException - if input is exhausted
int nextInt() Scans the next token of the input as an int. InputMismatchException - if the next token is not a valid boolean
NoSuchElementException - if input is exhausted
string nextLine() Advances this scanner past the current line and returns the input that was skipped. NoSuchElementException - if no more tokens are available