6.096 Quiz 2 Solutions

Summary

Question Mean Score StdDev Question Mean Score StdDev
1   9  
2   10  
3   11  
4   12  
5   13  
6   14  
7   15  
8   Total  

Question 1

Assume the following class definition:

Also assume that we begin our Java application with class Main. Which of the following could be the missing "startup code" -- the first code to be executed by Java?

  1. public static void main( String[] args ){

  2.     System.out.print("Args are ");
        for (int i = 0; i < args.length; i = i + 1){
            System.out.print(args[i] + " ");
        }
    }

  3. public static void Main( String[] args ){

  4.     System.out.println("Main called....");
    }

  5. public void main( String[] args ){

  6.     if (args.length == 0) {
            System.out.println("No arguments provided.");
        }
    }

  7. public static void main( String args ){

  8.     System.out.println("Args are " + args);
    }

  9. public static void main(){

  10.     System.out.println("Starting up....");
    }

  11. public static String main( String[] args ){

  12.     return args[0];
    }

The correct answer is a. The first code called by a Java application must be a public static method named main that takes one parameter -- an array of String -- and returns nothing.

Answer b is incorrect because Java is case-sensitive and the method name begins with a capital M.

Answer c's main method is not static. That is, this main method belongs to instances of the Main class (created with new Main()), not to the class itself. Java apps always start with a static method, and may never create an instance of the startup class.

Answer d's main method takes a single String, rather than an array of String -- String[] -- as is required.

The main method in answer e doesn't take any parameters.

The method in answer f returns a String; Java requires that its startup method be void.

Question 2

Assume that the following classes are defined in the following packages:
 

class package

Point

java.awt

Double

java.lang

CalculatorGUI

Calculator

Wire

cs101.util

Foo

Bar

Also assume that you are writing code in the Calculator package. Which of the following statements is true?

  1. You must import (part of) java.awt in order to be able to refer to java.awt.Point.
  2. You must import (part of) java.awt in order to be able to refer to Point.
  3. You must import (part of) java.lang in order to be able to refer to Double.
  4. You must import (part of) Calculator in order to be able to refer to CalculatorGUI.
  5. You must import (part of) cs101.util in order to be able to refer to cs101.util.Wire.
  6. You must import (part of) Foo in order to be able to refer to Bar.

The correct answer is b. An import statement doesn't change what you can access, it only changes how you can name it when you're accessing it. The import statement referred to in b allows you to refer to java.awt.Point simply as Point. You could refer to it as java.awt.Point even without an import statement. This is the problem with both choic a and choice e: you can use the long form of the name even without an import. Choice c is incorrect because you never need to import java.lang; you can always use the short form of names in the java.lang package. Choice d is incorrect because you are (by assumption) already in the Calculator package; you shouldn't have to import the package you're in! And choice f suggests importing a class so that you can refer to a package; this is backwards.

Question 3

Assume the following class definition:

After we create an AlarmClock instance --

-- how many animacies (Threads, execution paths) can be active in that object simultaneously?

  1. 0: nothing is ever active inside myClock.
  2. exactly 1: the one executing myClock's run() method.
  3. exactly 1: only one method of myClock may be in process at a time (even on a multi-processor machine), so either run or setTime may be called, but not both.
  4. 1 or 2: exactly one executing myClock's run() method, and at most one other executing myClock's setTime method.
  5. 1 or more: there will always be at least one current execution of myClock's run() method. In addition, there may be other excutions of either run or setTime.
  6. no more than 5: Java's language definition has a hard limit of 5 Threads per object.

The correct answer is e. When a new AlarmClock is created, one animacy is created and started by the constructor. In addition, since both run and setTime are public methods, either may be called from the outside an arbitrary number oftimes. There is no limit on how many methods may be active in this object simultaneously.

Question 4

Assume the following class definition. (This is the same code as the previous question's.)

Which of the following statements is true?

  1. There are no (potential) concurrency problems with the definition of AlarmClock as given.
  2. There is a (potential) concurrency problem because the Thread is started before the constructor exits.
  3. There is a (potential) concurrency problem because run might change the time (mins or hours) in the middle of a setTime.
  4. There is a (potential) concurrency problem because some executions of the while loop in the run method will change mins but not hours.
  5. There is a (potential) concurrency problem because the constructor calls setTime.
  6. There is a (potential) concurrency problem because the call to Thread.sleep might be interrupted.

The correct answer is c. The changes to hours and mins are interdependent, and it is important to do both at once -- or neither. That is, the change should be atomic -- nothing should be able to get in the middle. A problem could arise in this code if, for example, the time were 6:59 and there was a call to setTime( 11, 30 ). The run methodsetTime might decide that mins would become 60, set it to 0 instead, then start to increment the hours from 6; in the meantime, the call to setTime might set hours to 7; run might set hours to 1; and setTime might set mins to 30. The time would then be 7:30 instead of either 11:30 or 7:00.

There are several other ways in which the concurrency problems in this class could play out. However, none of the other choices in this question reflect concurrency problems. There is nothing left to happen in the constructor after starting the Thread, so choice b is not a problem. Choice d is a feature, not a bug. (When the clock ticks at 3:15, hours doesn't need to be changed.) Choice e is a nice example of code reuse, certainly not a concurrency problem. (The same thread executes the constructor and (its call to ) the setTime method; no concurrency!) Similarly, choice f does not refere to a concurrency situation; the sleeping Thread might be interrupted, but nothing bad comes of this and no second Thread need be involved.

Question 5

Assume the following class definition. (This is the same code as the previous question's.)

Which of the following modifications would not change the behavor of the code above?

  1. We could replace the call to this.spirit.start() with a call to this.run().
  2. We could replace the lines
         if ( ( hours > 0 ) && ( hours <= 12 )
              && ( mins >= 0 ) && ( mins < 60 ) ) {
    with
         if ( ( 0 < hours <= 12 ) && ( 0 <= mins < 60 ) ) {
  3. We could replace the lines
         try {
             Thread.sleep(1000);
         } catch( InterruptedException e ) {}
    with
         Thread.sleep(1000);
  4. We could replace the lines
         System.out.println("The time is "
                             + mins + " minutes after "
                             + hours + " o'clock." );
    with
         System.out.print( "The time is " );
         System.out.print( mins + " minutes after " );
         System.out.println( hours + " o'clock." );
  5. We could replace the line
         if ( this.hours == 13 ) {
    with
         if this.hours > 12 {
  6. We could replace the lines
         this.spirit = new Thread( this );
         this.spirit.start();
    with
         this.spirit = new Thread( this ).start();

The correct answer is d.

The difference between calling this.spirit.start() -- which ultimately calls this.run() -- and calling this.run() directly is that a Thread's start() method causes that other animacy to call the run method, rather than the calling animacy. That is, this.run() means I do the work; this.spirit.start() means I ask someone else to.

There are no three-way comparison statements in Java; choice b is simply illegal.

Choice c would mean that the run method would throw an exception, which should be declared, and would change the behavior of the code. Remember, an uncaught exception causes all execution to be exited -- the run method would no longer be running -- until the innermost enclosing (matching) catch statement is encountered. The code as written catches the exception, allowing run to continue.

Choice d uses a set of calls to System.out's print method instead of a single call to its println method. This is essentially functionally equivalent.

Choice e is syntactically incorrect -- the code won't compile -- because the parentheses around the if boolean condition are mandatory.

Choice f won't compile either, because a Thread's start method is void; you can't assign void to a name (this.spirit) of type Thread!

Question 6

Assume the following class definition:

Which of the following statements is true?

  1. Each ChocolateChipCookie instance has its own individual owner field, its own individual numChips field, and its own individual width field.
  2. Each ChocolateChipCookie instance has its own individual owner field and its own individual width field, but not its own individual numChips field.
  3. Each ChocolateChipCookie instance has its own individual numChips field and its own individual width field, but not its own individual owner field.
  4. Each ChocolateChipCookie instance has its own individual owner field, but not its own individual numChips field or its own individual width field.
  5. Each ChocolateChipCookie instance has its own individual width field, but not its own individual owner field or its own individual numChips field.
  6. Each ChocolateChipCookie instance has its own individual numChips field, but not its own individual owner field or its own individual width field.

The correct answer is e. Attributes marked static belong to the class -- the recipe object -- while those not marked static belong to instances of -- cooked with -- the class, but not to the class itself. Type or final markings have no bearing on this issue.

Question 7

The following code is drawn from the file ButtonHandler.java in the Documentation Project.

This is the complete file except for (1) the package statement, (2) the body of the constructor, and (3) the missing line in the run method.

Which of the following is the missing line from the run method?

  1. this.handleButton( this.stateObj );
  2. this.buttonObjs[buttonID].handleButton();
  3. buttonID.handleButton();
  4. this.stateObj.handleButton( buttonID );
  5. ButtonObj.handleButton( buttonID );
  6. this.handleButton( buttonID );

The correct answer is b. The array buttonObjs maps from buttonID to the smart button object ( of type ButtonObj)that handles button buttonID. Each ButtonObj has a handleButton() method that actually does the work.

Choices a and f are incorrect because this -- the ButtonHandler instance -- doesn't have a handleButton method.

Choice c is incorrect because buttonID is of type int, and doesn't have anymethods.

Choice d is incorrect because this.stateObj is of type CalculatorState and doesn't have a handleButton method.

Choice e is incorrect because the handleButton method is not static and so belongs to individual ButtonObjs but not to the class itself.

Question 8

Which of the following statements is true?

  1. new RoadMachine().start() will print
    BaZoooooooooooom!
  2. new RoadMachine().run() will print
    BaVroom, vroom!
  3. ((Car) new RoadMachine()).run() will print
    BaVroom, vroom!
  4. ((Car) new RoadMachine()).run() will print
    Vroom, vroom!
  5. new RoadMachine().run() will print
    BaVroom, vroom!Zoooooooooooom!
  6. new RoadMachine().start() will not print anything.

The correct answer is f. Creating a new RoadMachine() won't print anything. Calling its start() method will return a String -- "Ba" -- but it won't print anything, either. This means that e, not a, is the correct behavior for new Roadmachine().start().

new RoadMachine().run() will print BaZoooooooooooom! (Remember the outside-in rule: Method lookup always starts from the outermost part of the object.)

Casting new RoadMachine() to type Carwon't change its behavior; it just changes what methods you can call.

Question 9

Which of the following statements is true?

  1. Every finite state machine must have a No-Op transition.
  2. Every state of a finite state machine must have an incoming edge for every possible transition.
  3. No state of a finite state machine may have a "self-edge" -- an edge from that state to that state -- for any non-No-Op transition.
  4. Every state of a finite state machine must have an outgoing edge for every possible transition.
  5. No state of a finite state machine may have more than one incoming edge for any particular transition.
  6. Every state of a finite state machine must have at least one outgoing edge that goes to another state.

The correct answer is d.

Question 10

Which of the following could be a legal Java constructor method for a class named Classification?

  1. public void Classification {
        super();

    }
  2. public Classification () {
        return this;

    }
  3. public Classification () {
        return new Classification();

    }
  4. public Classification( String name ) {
        super();

        this.name = name;
    }
  5. public Classification (int i) {
        this.number = i;

        super( i );
    }
  6. public Classification () extends Classic {
        super();

    }

The correct answer is d. Answer a is missing the (possibly empty) parameter list. Answers b and c have returns, not allowed in a constructor. Answer e invokes the superclass constructor in its second line; such an invocation must be the first line of code in a constructor. Answer f has a misplaced extends statement; this goes on the class declaration, not the constructor declaration.

Question 11

The following code is excerpted from the Calculator interface. It has been reformatted to fit this exam.

Which of the following statements is true?

You may assume that a modification "would change the meaning of the interface" if either (a) the interface definition would no longer be legal Java and (b) some proper uses of the interface (i.e., uses as it is intended to be used) would no longer work (without modification) after the change. You may also assume that no change beyond the one(s) specified in the answer would be made.

  1. If the declaration of getButton() in this interface were modified to read
        public abstract int getButton();
    it would NOT change the meaning of the interface.
  2. If the declaration of getButton() in this interface were modified to read
        public static int getButton();
    it would NOT change the meaning of the interface.
  3. If the declaration of getButton() in this interface were modified to read
        public double getButton();
    it would NOT change the meaning of the interface.
  4. If the declaration of getButton() in this interface were modified to read
        public getButton(); // no int
    it would NOT change the meaning of the interface.
  5. If the declaration of getButton() in this interface were modified to read
        public int getButton( int prevButton );
    it would NOT change the meaning of the interface.
  6. If the declaration of getButton() in this interface were modified to read
        public int getButton() {}
    it would NOT change the meaning of the interface.

The correct answer is a. All methods in an interface are implicitly abstract; making this explicit has no effect. Methods in an interface may not be static; choice b wouldn't compile. (Even if it would, it would change the meaning of the declaration: static things belong to classes (or interfaces), not to their instances.) Change c would mean you'd have to modify every call to getButton(), since it would now return a doubleinstead of an int. Choice d wouldn't compile; a method needs a return type. Choice e would require rewriting calls to getButton(), too, since they would need to supply an argument. Choice f is illegal in an interface; this declaration of getButton() is no longer abstract. It has a method body, though that body doesn't do anything; this is different from not having a method body.

Question 12

Continuing with the same code from the Calculator interface....

Which of the following statements is true?

Again, you may assume that a modification "would change the meaning of the interface" if either (a) the interface definition would no longer be legal Java and (b) some proper uses of the interface (i.e., uses as it is intended to be used) would no longer work (without modification) after the change, and that no change beyond the one(s) specified in the answer would be made.

  1. If the values declared for OP_MUL and OP_DIV in this interface were swapped, i.e.,
        public static final int OP_DIV = 11;
        public static final int OP_MUL = 10;
    it would NOT change the meaning of the interface.
  2. If the declarations of OP_MUL in this interface were modified to read
        public static final int OP_MUL = 10;
    it would NOT change the meaning of the interface.
  3. If the declarations of OP_MUL in this interface were modified to read
        public final int OP_MUL = 11; // no static
    it would NOT change the meaning of the interface.
  4. If the declarations of OP_MUL in this interface were modified to read
        public static int OP_MUL = 11; // no final
    it would NOT change the meaning of the interface.
  5. If the declarations of OP_MUL in this interface were modified to read
        public static final double OP_MUL = 11;
    it would NOT change the meaning of the interface.
  6. If the declarations of OP_MUL in this interface were modified to read
        public abstract static final int OP_MUL = 11;
    it would NOT change the meaning of the interface.

The correct answer is a. It is important that OP_DIV and OP_MUL have different values (otherwise you couldn't tell them apart), but if their values are never used directly -- i.e., they are always accessed using these names -- then the particular values assigned to them don't matter. After all, it's not like you're going to be computing OP_DIV + OP_MUL. (This would not qualfy as a "proper use" of the interface!)

Choice b would mean that we couldn't tell the difference between OP_DIV and OP_MUL -- a big problem!

Choice c would not compile; even if it would, it would mean that individual OP_MUL fields belonged to each instance, not to the interface itself.

Choice d doesn't compile either; interface fields are required to be both static and final. (It would also mean that someone could change the value of OP_MUL out from under you!)

Choice e would change OP_MUL from an int to a double; this would obviously require modifying some potential "proper uses" of the code. For example, you can't use a double as the comparison value in a switch statement.

Choice f wouldn't compile: a field can't be abstract. (It's not really clear what this would/could mean.)

Question 13

Which of the following statements is true of System.out.println?

  1. out is a static field of the class System; println is a static method of System.out.
  2. out is a static field of the class System; println is a non-static method of System.out.
  3. out is a non-static field of the class System; println is a static method of System.out.
  4. out is a non-static field of the class System; println is a non-static method of System.out.
  5. out is defined in package System; println is a static method of System.out.
  6. out is defined in package System; println is a non-static method of System.out.

The correct answer is b. System is a class (in package java.lang, so its full name is java.lang.System, but you can just call it System.) It has a static field, out, of type java.io.PrintStream. Every java.io.PrintStrream has a (non-static) println method. Note that the long form of the method name is java.lang.System.out.println!

Question 14

Consider the following code, which implements a simple flip-flop:

       public class Toggle {

           protected boolean currentValue = true;

           public boolean flip () {
               this.currentValue = ! this.currentValue;
               return this.currentValue;
           }

       }

Now consider the following statements.

            Toggle switch = ...  // * This is the starred line!

              if ( switch.flip() ) {
                  System.out.println("First case");
              } else if ( switch.flip() ) {
                  System.out.println("Second case");
              } else {
                  System.out.println("Last case");
              }

Assume that the first (starred) line assigns some (existing) Toggle instance to the name switch, but that we don't know whether switch.currentValue is true or false at the time of this assignment. Further assume that nothing other than the single sequence of execution appearing in this question affects the value of switch.currentValue.

Which of the following statements is true?

  1. If switch.currentValue is false immediately after the starred line is executed, the if statement will print (only) First Case.
  2. If switch.currentValue is false immediately after the starred line is executed, the if statement will print (only) Second Case.
  3. If switch.currentValue is false immediately after the starred line is executed, the if statement will print (only) Last Case.
  4. If switch.currentValue is false immediately after the starred line is executed, the if statement will print both First Case and Second Case, but not Last Case.
  5. If switch.currentValue is false immediately after the starred line is executed, the if statement will print both First Case and Last Case.
  6. If switch.currentValue is false immediately after the starred line is executed, the if statement will print First Case, Second Case, and Last Case.

The correct answer is a. At most one clause of a cascaded if/else/else... statement will be executed -- the first one ot be true. If the value of switch.currentValue is false immediately after the starred line, the first call to switch.flip() will return true. This will cause "First Case" to be printed, and the if statement will exit. None of the else clauses will even be tested.

Question 15

The class java.awt.Component has a method

This method is called by the Java runtime in an event-driven style whenever something happens that requires that the Component update its on-screen appearance. For example, the paint method is called when the Component is first made visible or whenever an overlapping (occluding) window is moved away.

Which of the following statements is true?

  1. In order to create a (subclass of) Component that has a specialized appearance, you must call Component's paint method.
  2. In order to create your own (subclass of) Component with a specialized appearance, you must define your own paint method that takes a Graphics as its only parameter.
  3. In order to define your own specialized paint method, you must be able to supply your own Graphics object.
  4. When the Java runtime calls the paint method, it supplies the relevant PaintEvent to the paint method.
  5. java.awt.Graphics extends java.awt.Event.
  6. java.awt.Graphics extends java.lang.Thread.

The correct answer is b. Note that this question is about event-driven programming, though its example is drawn from java.awt.

The idea behind event-driven programming is that someone else calls your event handler methods with the appropriate information. In this case, your component's paint method is an event handler. You can specialize the way in which it handles paint events by defining your own specialized paint method. (Since you're overriding java.awt.Component's paint method, your method should also take a Graphics as its only parameter.) Since paint is an event handler, you don't call it: the Java runtime does. When Java calls the paint method, it supplies the appropriate Graphics.