Exam 2 Solutions

Q1. [20 points] This question tests your knowledge of core Java concepts.


(a) Explain what "(x instanceof String)" means in Java.

Ans: x is a variable that references an object (i.e., it can't be null) and the actual type of that object is String or a subclass of String.

(b) Explain the difference between the actual type of an object and the apparent type of a variable?

Ans: The Actual Type of an object is the class from which it was constructed. The Apparent type of a variable is the type used when the variable is declared. The statement 'Object o = new Point (1,2)' is valid because the Actual Type of the object o is Point, but this is a sub-type of the Apparent type 'Object' which is valid in Java.

(c.1) What does it mean when a method overrides another method?

Ans: A method M in a subclass can override the definition of the method M in a superclass if they both have exactly the same signature (name and parameters). It means that method calls to method M will be redirected to the subclass definition of M based on the actual type of the object on which the method is invoked.

(c.2) Explain the concept of method overloading.

Ans: When two methods belong to the same class and they have different arguments (either by number of by type definition) than one can say that the methods are overloading the common 'name' by which they are both referenced.

(d) Explain the difference between checked exceptions and unchecked exceptions?

Ans: An Un-checked exception is a class that is a descendant of the RunTimeException class. A checked exception is a class that is a descendant of Exception but not RunTimeException.

Q2 [15 points] Write the specification for the following method in terms of REQUIRES/MODIFIES/EFFECTS. Do not make any change to the code below.

/**
* REQUIRES: ar != null and 0 <= b < ar.length
* MODIFIES: ar
* EFFECTS: The resulting array is a permutation
*          of the original elements with the
*          largest element placed in ar[b].
*          If ar[b] was already the largest
*          element, then ar is unchanged.
*/

public static void f(int [] ar, int b) {
  for (int i = 0; i < ar.length; i++) {
    if (ar[i] > ar[b]) {
        int tmp = ar[i];
        ar[i] = ar[b];
        ar[b] = tmp;
    }
  }
}
/**
* REQUIRES: ar != null and b equal or less than
*      the number of times the value in ar[0]
*      appears in the list.
* MODIFIES: ar
* EFFECTS: the resulting array ar is a permutation
*          of the original elements with the
*          b left-most values (ar[0] .. ar[b-1])
*          containing the same values. If b <= 1
*          then the array is unchanged.
*/

public static void f(int [] ar, int b) {
  for (int i = 1; b > 1; i++) {
    if (ar[i] == ar[0]) {
        b = b – 1;

        int tmp = ar[i];
        ar[i] = ar[b];
        ar[b] = tmp;
    }
  }
}

Q3. [20 points] There are at least five logical errors in the following code. The Example code is supposed to print nothing but it instead prints out "(0,0) is same". Circle the errors and suggest changes to make it work. You may suggest new lines of code to add, or suggest lines of code to remove.

Ans:
1. In SpecialPoint, the instance variable for z is not set. Either set it, or move the toString() method into Point and replace z,z with x,y
2. In Point.equals(), the class of the parameter must be 'Object' to conform to the java.lang.Object standard for equals
3. In Point.equals(), the code makes multiple faults
    3a) note that the reference 'this.x' is the same as 'x', so the lonely 'x' should instead be p.x
    3b) note that the reference 'this.y' is the same as 'y', so the lonely 'y' should instead be p.y
    3c) the '==' check is invalid (this will return true if both points are on the XY diagonal. Replace with '(this.x == p.x) && (this.y == p.y)'

/**
 
* Point in plane with (0,0) as upper left.
 
* x increases to right, y increases down.
 
*/
public class Point {
  /** x,y point in plane. */
  int
x;
  int
y;
   
  /** Equality Check. */
  public boolean equals (Point p)
{
    return (this.x - x == this.y - y);
  }

  /** Construct Point */
  public Point (int a, int b) {
    y = b;
    x = a;
  }
}


/**
 
* represents a point whose x value is
 
* the same as its y value.
 
*/
public class SpecialPoint extends Point {
  /** Common value for both x and y. */
  int z;


  /** Constructor */

  public SpecialPoint (int z) {
    super (z,z);

  }

  /** Represent as String. */
  public String toString () {
    return "(" + z + "," + z + ")";
  }
}

/**
 
* Test code
 
*/
public class Example {
  public static void main (String [] args) {
   
Point p = new SpecialPoint(5);
   
Point q = new Point (3,3);
    if
(p.equals(q)) {
     
System.out.println (p + " is same");
    }
  }
}

Q4. [20 points] You have been given the task of writing a stand-alone iterator that takes a String object of length n and emits n String objects of length 1, one at a time, representing the individual characters from the String in order from left to right. You must show the (a) implementation, and the (b) specification of each method in StringIterator (including any constructor). 

Given a java.lang.String object 's', recall that (a) s.length() returns the length of the string; and (b) s.substring (x,y) returns the substring of the original string from character position 'x' in the string up to, but not including, position 'y' where positions are counted from zero. Thus, if s represents the string "Dilbert", then s.substring(0,3) is the String "Dil", while s.substring (3,4) is the string "b".  

You must provide the implementation of the class StringIterator and the specification for each method (including the constructor). Do not write the Abstraction Function or Representation Invariant). On the facing page to the right, write your answer.

 

/** Iterator for String. */
public class StringIterator implements java.util.Iterator {
   /** Current location in iterator. */
   int idx;

   /** String over which iteration is taking place. */
   String str;

   /**
    * Construct Iterator.
    *    REQUIRES: s != null
    */
   public StringIterator(String s) {
      if (s == null) {
         s = "";  // be gracious and let null be treated as empty string.
      }

      str = s;
      idx = 0;
   }

   /**
    * Determines whether Iterator has any more elements to emit.
    *    EFFECTS: returns true if idx < str.length()
    */
   public boolean hasNext () {
     return idx < str.length();
   }

   /**
    * Returns the next single-character string as an object
    *    REQUIRES: idx < str.length();
    *    MODIFIES: this
    *    EFFECTS: returns String object representing ith character in original string.
    */
   public Object next() {
      if (! hasNext()) {
        throw new NoSuchElementException ("String has no more characters.");
      }
   }

   /**
    * Remove operation is not supported.
    */
   public void remove () {
     throw new UnsupportedOperationException ("remove invalid on StringIterator.");
   }
}

Q6. [25 points] This question tests your knowledge of the Abstraction Function and the Representation Invariant concepts. You are given the task of defining a Java class to represent a date in the modern day calendar. If an object of this class represented today’s date, its toString() method would return "Tuesday November 30 2004".

This Date class is responsible for ensuring that only valid dates are constructed (i.e., "Wednesday November 31 2004" is invalid, for example, because November has 30 days). The Date class provides the methods used below (note: You must define the signature for the constructor):

Date dt = new Date (...);   // info for Tue 11/30/04
Date df = new Date (...);   // info for Fri 12/3/04
String wd = dt.getWeekday();
String m = dt.getMonth();
int d = dt.getDay();
int y = dt.getYear();
System.out.println (wd +
" " + m);

System.out.println (d + " " + y);
System.out.println (dt.difference(df) +
" days");

Output from code to the left:

Tuesday November
30 2004
4 days

DO NOT PROVIDE THE IMPLEMENTATION! YOUR ONLY TASK IS TO DEFINE (a) [10 points] the Abstraction Function for the Date class; (b) [10 points] the Representation Invariant for the Date class; and (c) [5 points] the signature of the constructor method.

Ans: There is no single answer to this question. Here are four to choose from. Which do you like best, and why? They all receive full credit

(A) Represent date as int for the number of days since January 1, AD 1.

Abstraction Function


Representation Invariant

Constructor:

/**
* Constructs a date or throws IllegalArgumentException if numDays < 0.
*/
public Date (int numDays) throws IllegalArgumentException { ... }

(B) Use Strings for WeekDay and Month, use ints for day-in-month and year.

Abstraction Function


Representation Invariant

Constructor:

/**
* Constructs a date or throws IllegalArgumentException if combination of values is inappropriate.
*/
public Date (String weekDay, String month, int day, int year) throws IllegalArgumentException { ... }

(C) Use four ints for all values.

Abstraction Function


Representation Invariant

Constructor:

/**
* Constructs a date or throws IllegalArgumentException if combination of values is inappropriate.
*/
public Date (int weekDay, int month, int day, int year) throws IllegalArgumentException { ... }

(D) Use three ints for all values, and calculate day-of-week on demand.

Abstraction Function


Representation Invariant

Constructor:

/**
* Constructs a date or throws IllegalArgumentException if combination of values is inappropriate.
*/
public Date (int month, int day, int year) throws IllegalArgumentException { ... }