CS56—Midterm Exam 2
WITH ANSWERS AND DISCUSSION
E02, W12, Phill Conrad, UC Santa Barbara
Thursday, 03/01/2012


IMPORTANT: Unless otherwise stated, all of the questions on this page pertain to programming in Java.
Do not consider any other programming language in your answer, unless the questions specifically calls for it.

Discussion of questions 1-6: Covered in textbook chapter 3,9 and homework H07.

Most students did well on this page: perfect papers were 47/73 (64% of the class).

47/73: -0 (30/30)
7/73: -2 or -3 (27-28/30)
8/73: -5 or -6 (24-25/30)
9/73: -9 to -13 (17-21/30)
12/73: -26 to -14 (4-16/30)

  1. (5 pts) Under what circumstances can a variable of a primitive type take up space on the stack?
    (If never, write "never").

    Answer: When it is a local variable in a method




  2. (5 pts) Under what circumstances can a variable of a primitive type take up space on the heap?
    (If never, write "never").


    Answer: When it is an instance variable in an object. (Also acceptable for partial credit: when an array of a primitive type is created. partial credit, because that is a just a special case of the correct answer, and the question was asking for a general description, not an "example".)



  3. (5 pts) Under what circumstances can a variable of a reference type take up space on the stack?
    (If never, write "never").
    (Note: this question refers to the reference variable itself, not the object referred to.)


    Answer: When the reference is a local variable in a method. The question was very specific about referring to the reference variable itself, not anything about the object referred to.



  4. (5 pts) Under what circumstances can a variable of a reference type take up space on the heap?
    (If never, write "never").
    (Note: this question refers to the reference variable itself, not the object referred to.)


    Answer: When the reference is an instance variable of an object.



  5. (5 pts) Under what circumstances can a reference refer to (i.e. "point to") an object on the stack?
    (If never, write "never").


    Answer: NEVER
  6. (5 pts) Under what circumstances can a reference refer to (i.e. "point to") an object on the heap?
    (If never, write "never").

    Answer: ALWAYS (unless the reference is null.)

    Discussion, problems 7,8,9 (20 points).

    25/73 students (~34%) got a perfect 20/20 on this page.

    25/73: -0 (25/25)
    9/73: -3 (22/25)
    11/73: -5 (20/25)
    11/73: -6 to -8 (17-19/25)
    9/73: -9 to -11 (14-16/25)

    8/73: -13 to -16 (9-12/25)

  7. (5 pts) Consider the following code excerpt:
    public final class Foo {
    ... // code continues from here
    

    In this context, what does the word final signify about the class Foo?

    Answer: The class cannot be extended.

    Note: in this context, it does NOT mean that instances of the class cannot be changed via setter methods.

  8. Suppose you want to create a new type of user-defined exception, a checked exception, called GauchoCodeViolationException


    1. (5 pts) Write the minimum amount of code that would accomplish this.

      Answer:

      public class GauchoCodeViolationException extends Exception {}



    2. (5 pts) What file would you put this code in?


      Answer: GauchoCodeViolationException.java


  9. (5 pts) Briefly, what is the purpose of a layout manager?
    Please be as precise as you can, using specific Java terminology.


    Answer: A layout manager allows the programmer to turn over the exact sizing and relative positions of widgets in a JComponent or other kinds of widget container to a piece of code that manages the size and positions (i.e. the "layout" on the screen) according to predefined rules. Without a layout manager, the programmer would have to specify the exact pixel location of each widget along with its size. The purpose of a layout manager is to allow the programmer to specify a "high level policy" for layout of the widgets without having to be concerned with the low level details.




  10. (5 pts) Briefly, under what circumstances would you want to make a class
    implement the Serializable interface (more specifically, java.io.Serializable)?


    Answer: when we want to encode the state of an object in a sequence of bits, so that we can store it to a file and read it into another running java program at a later time---or send it over a network to another running java program.

    Discussion: Most common error was saying something like: "when we want to save the state of an object"—which is not quite enough. Keep in mind that a "variable" to which we have a reference saves the state of an object (albeit on the heap, and only while the program is running and there is at least one active reference to that object.) You need to go further and specify "where" we are saving (making it clear that this 'saving' outlives the program.)

    21/73: -0
    36/73: -1
    2/73: -2
    6/73: -3
    8/73: -5



  11. Suppose a class implements the ActionListener interface
    (more specifically, java.awt.event.ActionListener)

    Discussion: Breakdown of deductions for problem 11:

    51/73: -0 (15/15)
    7/73: -2 (13/15)
    6/73: -3 (12/15)
    2/73: -4 (11/15)
    3/73: -5 (10/15)
    2/73: -8 (7/15)
    1/73: -10 (5/15)
    1/73: -11 (4/15)


    1. (5 pts) What is the purpose of having an instance of such a class—i.e. in what context would a class that implements ActionListener be useful?

      Answer: Typically an ActionListener is useful when we have a widget that's part of a Swing GUI—e.g. a JButton, JTextArea, etc.—and we want something to "happen" when that button is clicked, when text is entered, etc.—i.e. anytime there is an "event" taking place on that widget. If we want some code to be run when the event takes place, we have to create an instance of a class that implements ActionListener, implement the method that is invoked when the event occurs, and set the action listener for the widget.




    2. (5 pts) Objects that implement ActionListener often end up being "inner classes".
      What kinds of objects are typically the "outer classes" in this circumstance?

      Answer: either a JFrame, JComponent, or JPanel---or some other object that is art of a GUI implementation—either a window, a widget, or a container in which widgets are "layed out" by a layout manager. The outer class has all the widgets as instance variables, and registers the ActionListener events for those objects.




    3. (5 pts) Why is this "inner class/outer class" relationship a frequently used design—i.e. what is the advantage of making an ActionListener be an "inner class"—as opposed to not doing that?

      Answer: There are at least two reasons that would be acceptable answers, and it depends on what "alternative" you are contrasting the inner/outer class design with.

      If you are contrasting the inner/outer class design with making the ActionListener a whole separate class—then the advantage is that the ActionListener instance implementing as an inner class has access directly to the private instance variables and methods of the outer class, and vice-versa. Implementing the ActionListener as a separate class means that the object containing all the "state" for the GUI and the ActionListener object have to communicate via public method calls only—and this may be cumbersome, and expose parts of the internal workings that we might not want to expose.

      If you are contrasting the inner/outer class design with having the class that "would have been the outer class" implement ActionListener itself, i.e. making the this object be the one that that is acting as the ActionListener, then the advantage is different. In this case, both designs have the advantage that the actionPerformed() method has direct access to the private instance variables and methods, so that isn't the crucial distinction. In this case, instead, the advantage you may cite is that, since you can have more than one inner class implement ActionListener, you can create different ActionListeners that behave differently for different widgets. If "this" is the only ActionListener, then you only get one "flavor" of ActionListener.






  12. For this question, you need the handout that came with this exam—a handout with code for these files:
    Book.java, Product.java, Shippable.java, Song.java

    You may assume that all of the code on the handout compiles—I've checked that this is true.
    Now consider the following code, which does contain some errors, and as a result, will NOT compile.
    1public class Q1 {
    2 public static void main (String [] args) {
    3
    4 Book gp = new Book("Pratchett","Going Postal",799,0.15);
    5 Song br = new Song("Lady Gaga","Bad Romance");
    6 Product slts = new Song("Nirvana","Smells Like Teen Spirit",79);
    7 Shippable hp = new Book("Rowling","Harry Potter & the Polymorphic Polyp",652,1.5);
    8 Shippable ttc = new Shippable("Dickens","Tale of Two Cities",999,1.5);
    9
    10 System.out.println("a:" + gp.getTitle());
    11 System.out.println("b:" + br.getArtist());
    12 System.out.println("c:" + br.getPrice());
    13 System.out.println("d:" + slts.getPrice());
    14 System.out.println("e:" + slts.getTitle());
    15 System.out.println("f:" + hp.getPrice());
    16 System.out.println("g:" + hp.getWeight());
    17 System.out.println("h:" + hp.getTitle());
    18 System.out.println("i:" + ttc.getPrice());
    19 System.out.println("j:" + ttc.getPrice());
    20
    21 } // main method
    22} // class Q1
    Please do things with this "broken" code for the Q1 class:

    1. (15 pts) Several lines need to be eliminated from this file in order to make it compile.
      Find the lines that are bogus, and draw a line through each of them.

      Hint: By "several", I mean more than 2, and fewer than 10.
      Start by determining which, if any, of the constructors are bogus.
      Then, eliminate any lines that refer to the variables created on those lines.
      Finally, check all of the remaining method calls.

      You will lose points for striking lines that are not bogus, and you will lose points for failing to strike lines that arebogus. So, choose wisely.


      Here is the answer, with the lines of code that are bogus commented out.
      1public class Q1_answer { 2 public static void main (String [] args) { 3 4 Book gp = new Book("Pratchett","Going Postal",799,0.15); 5 Song br = new Song("Lady Gaga","Bad Romance"); 6 Product slts = new Song("Nirvana","Smells Like Teen Spirit",79); 7 Shippable hp = new Book("Rowling","Harry Potter & the Polymorphic Polyp",652,1.5); 8 // Shippable ttc = new Shippable("Dickens","Tale of Two Cities",999,1.5); 9 10 System.out.println("a:" + gp.getTitle()); 11 System.out.println("b:" + br.getArtist()); 12 System.out.println("c:" + br.getPrice()); 13 System.out.println("d:" + slts.getPrice()); 14 // System.out.println("e:" + slts.getTitle()); 15 // System.out.println("f:" + hp.getPrice()); 16 System.out.println("g:" + hp.getWeight()); 17 // System.out.println("h:" + hp.getTitle()); 18 //System.out.println("i:" + ttc.getPrice()); 19 //System.out.println("j:" + ttc.getPrice()); 20 21 } 22 23 24}
    2. (15 pts) After striking through the bogus lines, the remaining code should compile and run. So, indicate what the output will be (if any) below. Be precise. If there will no output, write "no output".

      a:Going Postal
      b:Lady Gaga
      c:99
      d:79
      g:1.5

      Discussion: 29/73 students got a perfect score for this problem. The material here comes from Chapters 7 and 8; and we reviewed it in detail in the last class before the exam.

      29/73: -0
      4/73: -3
      9/73: -6
      4/73: -9
      8/73: -12
      13/73: -18
      1/73: -21
      1/73: -24
      4/73: -30

End of Exam

Total points: ?

Handout for E02, CS56, W12

Product.java

1/** something that can be sold */
2public abstract class Product {
3
4 /** get the price (in cents) */
5 public abstract int getPrice();
6
7}

Shippable.java

1/** something that can be shipped */
2public interface Shippable {
3
4 /** get the shipping weight in pounds */
5 public double getWeight();
6}

Book.java

1/** A Book */
2public class Book extends Product implements Shippable {
3
4 private int price;
5 private double weight;
6 private String author;
7 private String title;
8
9 public Book(String author, String title, int price,
10 double weight) {
11 this.author = author;
12 this.title = title;
13 this.price = price;
14 this.weight = weight;
15 }
16
17 public int getPrice() {return this.price;}
18 public String getTitle() {return this.title;}
19 public String getAuthor() {return this.author;}
20 public double getWeight() {return this.weight;}
21
22}

Song.java

1/** A downloadable Song */
2public class Song extends Product {
3
4 private int price;
5 private String artist;
6 private String title;
7
8 public Song(String artist, String title, int price) {
9 this.artist = artist;
10 this.title = title;
11 this.price = price;
12 }
13
14 public Song(String artist, String title) {
15 this(artist,title,99);
16 }
17
18 public int getPrice() {return this.price;}
19 public String getTitle() {return this.title;}
20 public String getArtist() {return this.artist;}
21
22}