CSE143 Autumn Quarter
University of Washington
Midterm Exam #1
Friday, October 25, 2002 

Mouse over the colored box to see a question's answer

  Closed book, closed notes, closed neighbor, no calculators
1 point per question except as noted

This is the "as intended" version of the exam, including the corrections that were announced in class.

 

.
public class tester {

    int countSoFar = 2;

    private static void myIncrement(String [] args) {

        countSoFar++;

}

...

} //end class

In the code shown, is there a syntax error?

A.  yes, instance variables must be declared public, private, or protected.

B.  yes, methods cannot be private

C. yes, myIncrement cannot reference countSoFar

D. yes, class names must start with an upper case letter

E. no syntax error


C.

 
.
An eccentric professor claims that the keyword "abstract" in Java has two fairly distinct uses.  It really means _________ when used to describe a class.

1. cannot be modified

2. cannot be overriden

3. signature only

4. cannot be instantiated

A. 1 only

B. 2 only

C. 3 only

D. 4 only

E. More than one of 1, 2, 3, or 4


D. cannot be instantiated (only)

 
.
An eccentric professor claims that the keyword "abstract" in Java has two fairly distinct uses.  It really means ________ when used to describe a method.

1. cannot be modified

2. cannot be overriden

3. signature only

4. cannot be instantiated

A. 1 only

B. 2 only

C. 3 only

D. 4 only

E. More than one of 1, 2, 3, or 4


3. C -- signature only

 
.
Oscar and Tosca had their first daughter shortly after finishing high school.  Oscar is now 1000 years old and little Toscetta is 100 (in the same number base).  Oscar's age (base 10) is ____ (under reasonable assumptions).  All values in the choices are base 10; all ranges are inclusive

A.  between 15 and 19

B.  between 20 and 24

C.  between 25 and 29

D.  between 30 and 34

E.  greater than 34

C.  Proceed by exploration: try a base or two and see what you get.  

In base 2, the ages are 8 and 4.  In base 3, the ages are 27 and 9, so Toscetta would have been born when Oscar was 18, consistent with a typical high school graduation age.  In base 4, the ages are 64 and 16.  For Oscar to graduate from high school at age 4 or age 48 is not a reasonable assumption -- certainly not when compared with graduation at 18.  In bases above 4, Oscar's age is even more unreasonable.

 
 

Looking at this code (assume it compiles without error), what can you say about MissingPeanutException?

public Integer findPeanut(Cupboard cub) {

try {

    Integer pnum = cub.findPeanut( );

    } catch (MissingPeanutException pe) {

        safew = new Safeway();

        safew.buyPeanuts();

    }

...

}// end method

a. MissingPeanutException is a checked exception

b. MissingPeanutException is an unchecked exception

c. MissingPeanutException might be checked or unchecked (insufficient information)

d. MissingPeanutException is the name of a local variable

c.  You can't tell.  Since the exception is caught, the method doesn't have to declare it in a "throws", even if it were a checked exception.

A text file contains 100 (ASCII) characters.  A Java program reads the file into an array of Java chars.  How large must the array be to hold exactly this much data?

a. 50 bytes

b. 100 bytes

c. 200 bytes

d. 400 bytes

e. Depends on the local language (English, Chinese, etc.)

c. ASCII chars are one byte, Unicode 2 bytes

.
In a Java library, you notice a class named NewswireReader.  Assuming common Java naming conventions, what would be reasonable to assume (subject to further verification, of course)?

1. NewswireReader extends Reader

2. NewswireReader extends Newswire

3. NewswireReader expects a byte stream

4. NewswireReader expects a character stream

 

A. 1, 2, 3 (only)

B.  1, 2, 4 (only)

C. 3 only

D. 4 only

E. 1 and 4 (only)


E. extends Reader, expects (Unicode) characters.  It is conventional to use Reader in connection with character streams.

.
Study this code.  The compiler will complain that C2 should be declared abstract.  Why?
    
    class abstract C1 {
         public abstract boolean meth1();
         public boolean meth1(String s) {
         		return s.equals("secret password");
         		}
         public void meth2() {}
    } //end C1
    class C2 extends C1 {
    	public boolean meth1(double d1, double d2) {
         		return Math.abs(d1-d2) < 0.000001;
        }
    }  // end C2

A. Because no constructors have been defined in C2

B. Because meth1 may not have more than one signature

C. Because the empty method meth2 has not been overriden in C2

D. Because C2 fails to implement a certain method declared in C1.

D. [The actual wording on the test for D was "Because one version of meth1 has not been implemented in C2".  This wording was allowed to stand without change, even though the alternate wording is a little better.]  The method with signature boolean meth1 () is abstract in C1, so an implementation must be supplied in any non-abstract class which extends C1.  The status of other methods, including constructors, is irrelevant to the problem.
 
 
.
X, Y, and Z are names of classes or interfaces.  Assume the following code compiles without error:
    	X v1 = new Y();
    	Z v2 = v1;
    
Just from this, what can you tell?

1. X could be an interface

2. Y could be an abstract class

3. Z must be a superclass (or "superinterface") of X

A. 1 only

B. 2 only

C. 3 only

D.  1 and 3 only

E.  All of 1, 2, and 3


D.  From line 1 alone, X can be anything; Y cannot be an abstract class or interface, and must be a subclass of X.  So v1 is a Y dynamically, BUT -- v1 is an X statically.  So in line 2, v1 is a Z implies that X is a subclass of Z (not that Y is a subclass of Z).  

 
.
Given the following code (all in the same TestClass.java file), if the code compiles. what is printed out when the main method is executed? 
public class TestClass {
public static void main(String[] args) {
	A anA = new B();
	anA.m1();	
	} //end main
} //end TestClass


class A  {
	void m1() { 
		System.out.println("1");
		this.m2();
		System.out.println("2");
	}
	void m2() {
		System.out.println("3");
	}
} //end A

class B extends A {
	void m2() {
		System.out.println("4");
	}
} //end B
//end .java file

    

A. 132

B. 142

C. Won't compile, because main calls a non-static method.

D. Won't compile, because there is no constructor for class B

E. Won't compile, because m2 is defined more than once. 

B: 142.  [The output in choices A and B should have been formatted vertically, since it is produced by println rather than print.]

anA has static type A, and dynamic type B.  B is a subclass of A.

m1 is called on anA.  This is dispatched to the m1 of A, since B (the dynamic type) doesn't have an overriden m1.  Inside m1, m2 is called, and since the object (this) is of dynamic type B, and B has an overriden m2, the m2 of B is called rather than the m2 of A.


 
.
Class BCap extends Hat.  A programmer writes the following two consecutive statements:
    Hat b=new BCap();
    b.foo();

What circumstance(s) would make the code wrong  (either have a syntax error or a run-time error)?

I. BCap has a method foo but Hat doesn't

II. Hat has a method foo but BCap doesn't

III. Neither Hat nor BCap have method foo() 

A. I only

B. II only

C. III only

D. I or III

E. II or III 

[An important correction was made as the test was taken:  the very first sentence was changed to "Class BCap extends Hat, which extends Object."

D:  I, because the static type of b is Hat, which doesn't have foo, so the compiler doesn't know that a b is there at run-time.  Note the distinction between b (the object) having a method and Hat (the class) having a method.  III is true; the "which extends Object" is needed to rule out there being additional superclasses of Hat which might implement foo.

Note that the question is "what would make it wrong", not "what would make it right".  This means that issues of private vs public, etc. don't matter.  There are lots of things that could make the code wrong in addition to the choices listed.


 
.
throw vs. throws

What is true about the use of these keywords within any given method?

A. A method will have at least one throw for every throws

B. A method will have at least one throws for every throw 

C. A method can never have both throw and throws

D. A method could have a throw  or throws but not have any try or catch.

A. A only

B. B only

C. C only

D. D only

E. A and B, i.e., there is exactly one throw  for every throws


D


 
.
Study the method below.  Form an idea of what it does.
    public static int findThem(String[] names, String prefix) {
        int result =0;
        for (int s = 0; s < names.length; s++) {
            if (names[s].startsWith(prefix)) {
                result++;
            }
        }
        return result;
    } //end method
    
Now although we don't have a description of what the method is supposed to do, let's suppose that it does correctly fulfill its end of a reasonable contract between client and implementer (server).  In that case, which of the following are implementer responsibilities, i.e, things which the implementer guarantees to the client, if the client fulfills its side of the contract?

A. The return value is not negative.

B. If the return value is x, and the number of names in the array is x, and x >=1, and prefix.length >= 3, then names[0].charAt(2) == names[x-1].charAt(2).

C. names is not null

D. names.length >= 1

E. the variable named result never takes a value less than 0

A. A and B only

B. C and D only

C. C, D, and E only

D. A, B, and C only

E. All of A, B, C, and D.

A == A and B only.  E is a true statement, but it is not something the implementor guarantees to the client.  The client doesn't know or care if there even is a local variable named result.


 
.  Worth 2 MC questions
C1, C2, and C3 are variables of type HugeType, and at a certain point in the program, C2 is a clone of C1.  Then the following statements are excuted:;
 		if (C1 == C2) {
 			C2 = C3;
 		} else {
 			C2 = C3.clone(); 
 		}
    

Draw the picture ("official style") that results. Use the space to the right.

[Actually, .clone can throw a checked exception -- ignore that for this problem.

 


The boolean expression in the if statement is false.  The final picture has three names, each bound to a different object of type HugeType.



 
.   Programming Problem: worth 5 multiple choice problems
The Distance-Learning Math Tutor

Your company develops educational software.  The "Math Tutor" is intended for high-school math students throughout the state.  A student sits at a local computer and sees a math problem.  He or she figures out the answer and types it in.  The answer is transmitted on a stream to your company, where a program checks the answer for correctness and informs students of the results.

One particular type of problem is number conversion.  The student is given a number (base 10) and a radix, and must type in the correct string for that number converted to the radix base.  For example, if the number is 19 and the base is 6, the only correct answer is "31".  A GUI makes sure there are no extraneous characters (such as spaces), and that digits A,B,C, etc. (for radices above 10) are upper case. Your job is to implement the checkAnswer method for this type of problem.  On the next page, a fuller specification of the module is given.  Write your code on that page.  Don't change or add to the method header.

 

In response to questions, some additional clarifications for the whole class to hear.


 
.
    // instance variables, constructors omitted -- don't assume anything about them.
    //Assume the four parameters are all valid (don't error-check them).
    //Don't invoke any methods except those of the standard Java library.
    
   /** The method is called when the system detects that the student has finished typing an answer
     * and is ready to have the answer checked.
     * This method checks the answer for correctness, and replies with the appropriate message of 
     *     "Correct! U R A Genius!" or ":( "
     * The method also returns a value of true if the answer is correct, and false otherwise
     * 
\     * Exceptions of any kind are to be treated just like wrong answers.
     */
     boolean checkAnswer ( BufferedReader inputInfo, //the student's answer,
                                        //as a string, is read from this stream.
                                        //The stream is already open and ready to go
                                       
                           BufferedWriter output, //any message (String) is sent back to the student
                                        //on this stream.  The stream is open and ready to go.
                                        
                           int originalNumber, //the value the student is supposed to convert
                                        //to another base (radix)
                                        
                           int radix)    //the radix to which the student was supposed to convert
                                        //the original number
              {
 
    
    
    

    

 



 
.
 

 

//Solution code for above problem.  Method header is not repeated.
//A sample .java file with a simple test driver will also be posted.
              boolean result; //eventual value to return to the client
              String inputString; //place the string which the student typed in here
              try {
                   inputString = inputInfo.readLine();
                   int inputValue;
                   inputValue = Integer.parseInt(inputString, radix);
                   result = (inputValue == originalNumber);                   
              } catch (Exception e) {  //IOException also accepted -- see below
                    result = false;
              }
                   //Actually, parseInt can throw an IllegalNumberFormatException.
                   //This information was not on the handout, and it is an unchecked
                   //exception anyway, so not having a separate try/catch, or only
                   //having a catch (IOException e) was not marked down.
                   //You can argue that a single clause for Exception is best, because
                   //the requirement is to "treat ALL exceptions as wrong answers".
                   
              String messageToSend;
              if (result == true) {
                    messageToSend = "Correct! U R A Genius!";
              } else {
                    messageToSend = ":( ";
              }
              try {
                    output.write(messageToSend); //NOT System.out.println !!
              } catch (IOException e) {
                    //hard to know what to do here. even "result == false" is iffy.
                    // Maybe a diagnostic to System.out, or rethrow the exception
                    }
      
              return result;
} //end method