JMU CS446 - Software Analysis and Design
Help Policies Solutions Study-Aids Syllabus Tools
Sample Questions for Exam 1


  1. Discuss the purpose of each of the following:
    1. Assertions
    2. Localization
    3. Parameterized/Generic Collections
  2. Indicate the best match for each of the following:
    _____ Composite Pattern
    _____ Decorator Pattern
    _____ Iterator Pattern
    _____ Observer Pattern
    _____ Singleton Pattern
    _____ Strategy Pattern
    1. Loop independently of the aggregate
    2. Limit the construction of objects
    3. Ignore differences between individuals and groups
    4. Decrease Coupling
    5. Use a family of interchangeable algorithms
    6. Add capabilities to an object at run-time
  3. Some of the statements in the following fragment may not compile and some may cause an exception to be thrown at run-time. Write an "N" next to each statement that will not compile and an "E" next to each statement that will cause an exception to be thrown at at run-time.
        Number[]  n;
        Integer[] i = new Integer[2];
            
        i[0] = Integer.valueOf(0);
        n = i;
        n[1] = Double.valueOf(7.5);
        
  4. Given a method in the Statistics class declared as follows:
        public static int min(List<Comparable> data)
        

    will the following fragment compile (assuming everything has been imported properly)? Explain.

          List<Integer> data;
          // Instantiate and initialize data
          int m = Statistics.min(data);
        
  5. Why does java restrict upper bounded (i.e., covariant) collections to be "read only" at compile time? You may explain with an example.
  6. Implement a ShapeLabel class that extends JLabel javax.swing.JLabel and overrides its paint() method so that, instead of rendering text, it renders the shape. The constructor must have a single String parameter, and it must only accept the String objects "Circle", "Rectangle", "Square", and "Triangle". It must also have a setColor(Color c) method that can be used to set the Color that the shape will be rendered in.
  7. Carefully explain:
    1. The role of the model, view and controller in a GUI component.
    2. The difference between "check boxes" and "radio buttons" using ideas from the model-view-controller pattern.
  8. Explain the differences and similarities between extending a class and decorating an object.
  9. In the Java API, give an example of:
    1. The composite pattern.
    2. The model-view-controller pattern.
    3. The observer pattern.
  10. Create a ShapeColorAction that can be used to set the Color of a ShapeLabel (as described in an earlier question). Your implementation must extend AbstractAction javax.swing.AbstractAction , must have a constructor that is passed the associated ShapeLabel, and must use a JColorChooser javax.swing.JColorChooser . It need not use a "background thread" (i.e., a SwingWorker javax.swing.SwingWorker ).
  11. Given the following interface describing an IndexedGroup abstract data type:
    package collections;
    
    /**
     * The requirements of a group of elements that can be get/set
     * using an integer index.
     */
    public interface IndexedGroup<E>
    {
        /**
         * Get the element at the given index
         *
         * @param  index   The index of interest
         * @return         The element at the given index
         */
        public E get(int index) throws IndexOutOfBoundsException;
    
        /**
         * Set the element at the given index.  If the index does not yet
         * exist, it will be created (space permitting).  Some implementations
         * may throw an IndexOutOfBoundsException if the index is invalid.
         *
         * @param  index   The index of interest
         * @param  value   The new value for the given index
         */
        public void set(int index, E value);
    }
       

    complete the following FixedSizeIndexedGroup class:

    package collections;
    
    public class FixedSizeIndexedGroup<E> implements IndexedGroup<E>
    {
        Object[]    values;
        
    
        public FixedSizeIndexedGroup(int size)
        {
           values = new Object[size];
        }
    
        
        
        public E get(int index) throws IndexOutOfBoundsException
        {
        }
        
    
        public void set(int index, E value) throws IndexOutOfBoundsException
        {
        }
    }
       

    You may add private methods if you think they will improve your solution. Note: You may have to use some "unchecked or unsafe" operations.

  12. Modify your answer to the question above so that it implements the Iterable java.lang.Iterable interface. To do so, you should create an IndexedGroupIterator class that implements the Iterator java.util.Iterator interface. Note: The next() method should return null elements that are in the IndexedGroup.
  13. Justify the type of class (e.g., traditional, static nested, inner, local, anonymous) you used to answer the previous question.
  14. Modify your IndexedGroupIterator class so that it also has hasNextNonNull() and nextNonNull() methods that behave as their names imply. Why are these methods not likely to be used? (Hint: Think about the specification of the Iterator interface.)
  15. How might you change the design of the system above so that one could iterate through either all of the elements or all of the non-null elements using different iterators.
  16. The following model describes my current address book:
    1. Carefully interpret/explain this model.

      addressbook.png

    2. How can this model be improved?
    3. Build a new model that allows for people to be members of an organization. (Note: The organization should have one address and everybody associated with that organization should have that address. The organization may have a central phone number and email address and everybody associated with the organization may have one as well.)
    4. Are there other situations in which different people in an address book share some information? Is your model flexible enough to handle all of these situations? Why or why not?
  17. Consider the following design model:

    drawing.png

    1. What role in the composite pattern is played by:
      Shape


    2. What role in the composite pattern is played by:
      Line


    3. What role in the composite pattern is played by:
      Rectangle


    4. What role in the composite pattern is played by:
      Text


    5. What role in the composite pattern is played by:
      Drawing


    6. What method in this model plays the role (in the composite pattern) of:
      operation()


  18. In Java, a Map object (e.g., a HashMap) can contain only one value for each key. Hence, in order to keep a mapping of, say, students to grades, one has to be creative. One approach is to create a ManyValuedMap class that does not provide all of the functionality or a Map but delegates to an object that implements Map. For example:
    import java.util.*;
    
    
    public class ManyValuedMap<K,V>
    {
        private HashMap<K,ArrayList<V>>       delegate;
    
        public ManyValuedMap()
        {
            delegate = new HashMap<K,ArrayList<V>>();
        }
    
        // Returns all of the values associated with a key (or null)
        public ArrayList<V> get(K key)
        
        // Adds the value to the ArrayList associated with the given key
        public V put(K key, V value)
    
        // Removes the value from the ArrayList associated with the given key
        public V remove(K key)
    }
        

    Implement this class.

  19. As an alternative to the implementation of the ManyValuedMap above, one could extend the HashMap class as follows:
    import java.util.*;
    
    
    public class ManyValuedMap<K,V> extends HashMap<K,V>
    {
        // Searches through all of the values in all of the keys
        public boolean containsValue(Object value)
    
        // Returns the first value for this key
        public V get(Object key)
    
        // Returns all of the values associated with a key (or null)
        public Iterator<V> getValues(K key)
        
        // Adds the value to the ArrayList associated with the given key
        public V put(K key, V value)
    
        // Throws UnsupportedOperationException
        public void putAll(Map<? extends K,? extends V> m) 
        
        // Removes the value from the ArrayList associated with the given key
        public V remove(Object key)
    
        // Returns a Collection of all of the values associated with all keys
        public Collection<V> values()
    }
        

    Implement this class.

  20. Rather than extending the HashMap class as above, one could decorate a Map as follows:
    import java.util.*;
    
    
    public class ManyValuedMap<K,V> implements Map<K,V>
    {
        private  Map<K,ArrayList<V>>       decorated;
    
        public ManyValuedMap(Map<K,ArrayList<V>> decorated)
        {
            this.decorated = decorated;
        }
    
        // All of the methods required in the Map interface should
        // delegate to decorated as needed
    
    
        // Returns all of the values associated with a key (or null)
        public Iterator<V> getValues(K key)
        {
           Collection<V>    values;
           
           values = decorated.get(key);
           
           if (values != null) return values.iterator();
           else                return null;       
        }
    }
        

    Implement this class.

  21. In the Java API, give an example:
    1. The command or strategy pattern.
    2. An empty class.
  22. Various newspapers reported that former President Clinton's staff removed the W keys from all of the keyboards at the White House so that President Bush's staff would not be able to type "George W. Bush". While it was an interesting prank, it was not very subtle. A more subtle approach would have made use of the Model-View-Controller pattern to create a ClintonTextField that replaces 'W' and 'w' characters with spaces.

    With that in mind, you must complete the createDefaultModel() method in the ClintonTextField below and the insertString() method in the ClintonDocument below.

      import javax.swing.*;
      import javax.swing.text.*;
      
      /**
       * A JTextField that replaces 'W' and 'w' characters with spaces
       *
       */
      public class ClintonTextField extends JTextField
      {
        /**
         * Construct a new ClintonTextField
         */
        public ClintonTextField()
        {
            super();
        }
      
      
      
    
        /**
         * Create a Document (i.e., model) for this ClintonTextField
         *
         * @return  A ClintonDocument
         */
        protected Document createDefaultModel()
        {
    
    
    
        }
      }
      
      import javax.swing.text.*;
    
      /**
       * A Document that replaces all 'W' and 'w' characters with
       * spaces whenever a String is inserted into it.
       *
       */
      public class ClintonDocument extends PlainDocument
      {
      
        /**
         * Inserts content into the document after replacing all 'W' and 'w'
         * characters with space characters
         *
         * @param offs   The starting offset
         * @param str    The string to insert
         * @param a      The attributes for the inserted text
         */
        public void insertString(int offs, String str, AttributeSet a) 
                                 throws BadLocationException
        {
    
    
    
        }
      }
      
  23. Consider the following implementation of a CS446TextField:
        import java.awt.*;
        import javax.swing.*;
        import javax.swing.event.*;
        import javax.swing.text.*;
      
        public class CS446TextField extends    JPanel 
                                    implements DocumentListener
        {
          private JLabel           label;
          private JTextField       textField;
          private String           txt;
      
      
          /**
           * Construct a new CS446TextField
           */
          public CS446TextField()
          {
      	super();
      	txt = new String();
      	label = new JLabel("I Love");
      	textField = new JTextField();
      
      	setLayout(new BorderLayout());
      	add(label, BorderLayout.SOUTH);
      	add(textField, BorderLayout.CENTER);
      	
      	textField.getDocument().addDocumentListener(this);
          }
      
    
          /**
           * Handle insertUpdate events (required by DocumentListener)
           */
          public void insertUpdate(DocumentEvent de)
          {
      	label.setText(textField.getText());
          }
    
      
          /**
           * Handle removeUpdate events (required by DocumentListener)
           */
          public void removeUpdate(DocumentEvent de)
          {
      	label.setText(textField.getText());
          }
    
      
          /**
           * Handle changedUpdate events (required by DocumentListener)
           */
          public void changedUpdate(DocumentEvent de)
          {
          }
    
        }
        
    1. What will a CS446TextField look like immediately after (i.e., before any keys are pressed) it is added to a Container?
    2. Carefully explain what will happen if "CS446" is typed in a CS446TextField when it has the focus.
  24. Implement a PulsingLabel class that extends JLabel javax.swing.JLabel and uses a Timer javax.swing.Timer to interatively increase the font size four times and then decrease the font size four times (so that the text on the component appears to "pulse".
  25. Explain why, in a GUI-based application, lengthy tasks should be completed in a "background" thread (i.e., using a SwingWorker javax.swing.SwingWorker ). Give a specific example of what might "go wrong" otherwise.
  26. The Computer Science Department at JMU has developed an email system called JMUmble. In this system, arriving messages are handled by a PostOffice object. Depending on how the system is configured at runtime, one or more objects might need to know when a message arrives. The Department has currently implemented several such classes: ScreenFlasher (which makes the entire screen flash -- you always know when a message has arrived), PopularityTimer (which starts a clock that show the amount of time since the most recent message arrived), and Mumbler (which uses speech generation to read the name of the person that sent the message -- this is where the system got its name). Use the observer pattern to develop a class model of this system (in UML). You do not need to include the attributes of each class, only the operations/methods. Include comments that describe each operation/method.
  27. Complete the following PrimeNumbersTask class.
    public class PrimeNumbersTask extends SwingWorker<List<Integer>, Integer>
    {
      private ArrayList<Integer> primes;
      private int                current, numberOfPrimesToFind;
      private JTextArea          textArea;
    
      public PrimeNumbersTask(JTextArea textArea, int numberOfPrimesToFind) 
      {
        this.numberOfPrimesToFind = numberOfPrimesToFind;
        this.textArea = textArea;
        primes = new ArrayList<Integer>();
        current = 2;
      }
    
      public List<Integer> doInBackground() 
      {
        // TODO
      }
    
      private boolean isPrime(int n)
      {
        for (int i=2; i<n; i++)
        {
          if (n % i == 0) return false;
        }
        return true;
      }
    
      private int nextPrimeNumber(int start)
      {
        for (int n=start+1; n<Integer.MAX_VALUE; n++)
        {
          if (isPrime(n)) return n;
        }
        return -1;
      }
    
      protected void process(List<Integer> chunks) 
      {
        // TODO
      }
    }
    

    Your implementation must satisfy the following specifications:

    1. The doInBackground() method must iterate until the desired number of prime numbers has been found or until the task is cancelled.
    2. The doInBackground() method must return a List containing all of the prime numebrs found.
    3. Each time a prime number is found it must be "published".
    4. When a prime number is "published" it must be appended to the bottom of the JTextArea.
    5. Each time a prime number is the "progress" must be updated.

Copyright 2022