Review Questions for Midterm Exam (Sections 1.1 - 1.3)


  1. What is printed?

    	  String s1 = "bad";
    	  String s2 = s1;
    	  s1 = "fad";
    	  System.out.printf("%s %s\n", s1, s2);
    	

    Ans:

    	  fad bad
    	
  2. What is value of f(5)?

    	  public static int f(int n)
              {
                if (n < 2) {
                   return n;
                } else {
                   return f(n - 1) + f(n - 3);
                }
              }
    	

    Ans:

    	  1
    	

    But, the first 12 values are:

              f(0)  = 0
              f(1)  = 1
              f(2)  = 0
              f(3)  = 0
              f(4)  = 1
              f(5)  = 1
              f(6)  = 1
              f(7)  = 2
              f(8)  = 3
              f(9)  = 4
              f(10) = 6
              f(11) = 9
    
            
  3. Write the method max to returns the maximum of a and b:

    	  public static int max(int a, int b)
              {
                ...
              }
    	

    Ans:

    
    	  public static int max(int a, int b)
              {
    	     if (a < b) {
    	       return b;
                 } else {
                   return a;
                 }
              }
    
    or
    
    	  public static int max(int a, int b)
              {
    	     return (a < b ) ? b : a;
              }
    
  4. 1.1.4

    What (if anything) is wrong with each of the following statements?

    a. if (a > b) then c = 0;
    b. if a > b { c = 0; }
    c. if (a > b) c = 0;
    d. if (a > b) c = 0 else b = 0;
    

    Ans:

  5. 1.1.5

    Write a code fragment that prints true if the double variables x and y are both strictly between 0 and 1 and false otherwise.

    Ans:

    if ( (0 < x) && (x < 1) && (0 < y) && (y < 1)) {
         return true;
    } else {
         return false;
    }
    

    or just

    return 	(0 < x) && (x < 1) && (0 < y) && (y < 1);  
    	
  6. 1.1.6

    What does the following code print?

    
    int f = 0;
    int g = 1;
    for (int i = 0; i <= 6; i++)
    {
       System.out.printf("%d ", f);
       f = f + g;
       g = f - g;
    }
    

    Ans:

    	  0 1 1 2 3 5 8
    	

    Trace:

    i f g f = f + g g = f - g
    0 0 1 1 0
    1 1 0 1 1
    2 1 1 2 1
    3 2 1 3 2
    4 3 2 5 3
    5 5 3 8 5
    6 8 5 13 8
  7. 1.1.10

    What is wrong with the following code fragment?

    int[] a;
    for (int i = 0; i < 10; i++) {
       a[i] = i * i;
    }
    

    Ans: a is not initialized; no array is created.

  8. Write an class SumN that

    1. Prompts for an integer
    2. Reads an integer and stores it in an int N
    3. Computes the sum 1 + 2 + ... + N
    4. Prints the sum

    Ans:

    
    public class SumN
    {
      
      public static void main(String[] args)
      {
        int N;
        Scanner stdin = new Scanner(System.in);
    
        System.out.print("Enter an integer: ");
        
        int sum = 0;
        for(int i = 1; i <= N; i++) {
          sum += N;  // or sum = sum + N;
        }
        System.out.printf("sum = %d\n", N);
      }
    
    }
    
  9. Write an class FileSum that

    1. prompts for a file name, reads and stores the name in the String fname
    2. Computes the sum of the integers in the file.
    3. Prints the sum

    Ans:

    public class FileSum
    {
      
      public static void main(String[] args)
      {
        int N;
        String fname;
        Scanner stdin = new Scanner(System.in);
    
        System.out.print("Enter file name: ");
        fname = stdin.next();
    
        Scanner in = null;
        try {
          in = new Scanner(new File(fname));
        } catch(FileNotFoundException e) {
          System.out.println("Cannot open input file: " + fname);
          System.exit(0);
        }
    
        int sum = 0;
    
        while(in.hasNextInt()) {
          sum = sum + in.nextInt();
        }
    
        System.out.printf("sum = %d\n", N);
      }
    
    }
    
  10. 1.2.5

    What does the following code fragment print?

    String s = "Hello World!";
    s.toUpperCase();
    s.substring(6, 11);
    System.out.println(s);
    

    Ans: World

    (The "!" at position 11 is not included.)

    String is immutable. So s.toUpperCase() does NOT change s. Instead it returns a new String like s, but in upper case.

    Similarly, s.substring(6, 11) does NOT change s. Instead it returns a new String that is like the substring in s from position 6 (inclusive) to position 11 (exclusive).

    To change what String s references, we need to assign the new value to s:

    String s = "Hello World!";
    s = s.toUpperCase();
    s = s.substring(6, 11);
    System.out.println(s);
    

    Ans: WORLD

    The ! is not printed!

  11. 1.2.8

    Suppose that a[] and b[] are each integer arrays consisting of millions of integers.

    What does the follow code do? Is it reasonably efficient? Explain your answer.

    
    int[] t = a; a = b; b = t;
    

    Ans: Only references to the two arrays are copied, not the integers. So it is very efficient.

  12. 1.2.14

    Here is a portion of a Date class showing its override of the equals method:

    
    public class Date
    {
      private int month;
      private int day;
      private int year;
    
      public Date(int m, int d, int y) {
        month = m;
        day = d;
        year = y;
      }
    
      // ... Some date methods not shown
    
      public boolean equals(Object obj)
      {
        if (obj instanceof Date) {
          Date other = (Date) obj;
          if (month == other.month && day = other.day && year == other.year) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      }
    
    }
    

    A Transaction class has members of type String (who), Date, and double (the amount)

    Two transactions should be equal if the three data members of one are equal to the three data members of the other transaction.

    Write the equals method for Transaction.

    public class Transaction
    {
      private String who;
      private Date date;
      private double amount;
    
      public Transaction(String w, Date dt, double amt)
        who = w;
        date = dt;
        amount = amt
      }
    
      // ... Some date methods not shown
    
      public boolean equals(Object obj)
      {
    
    
    
    
    
      }
    
    }
    

    Ans:

    public class Transaction
    {
      private String who;
      private Date date;
      private double amount;
    
      public Transaction(String w, Date dt, double amt)
        who = w;
        date = dt;
        amount = amt
      }
    
      // ... Some date methods not shown
    
      public boolean equals(Object obj)
      {
        if (obj == this) {
          return true;
        }
    
        if (obj instanceof Transaction) {
          Transaction other = (Transaction) obj;
          return who.equals(other.who) && date.equals(other.date) && amount == other.amount;
        } else {
          return false;
        }
      }
    
    }
    
  13. What value is printed?

    Ans: 1

        1	
        2	
        3	public class M
        4	{
        5	  
        6	
        7	  public static int f(int[] arr, int i, int j)
        8	  {
        9	    int m;
       10	    int b, c;
       11	    
       12	
       13	    if (i == j) {
       14	      return arr[i];
       15	    } else {
       16	      m = (i + j) / 2;
       17	      b = f(arr, i, m);
       18	      c = f(arr, m + 1, j);
       19	      if (b < c) {
       20		return b;
       21	      } else {
       22		return c;
       23	      }
       24	  }
       25	
       26	  public static void main(String[] args)
       27	  {
       28	    
       29	    int a;
       30	    int[] A = new int[] A {1,6,3,9,10,11,5};
       31	   
       32	    a = f(A, 0, A.length - 1);
       33	
       34	    System.out.printf("a = %d\", a);
       35	  }
       36	
       37	}
    

    For any array C which elements of C will f assigned to a for the statement a = f(C, 0, C.length - 1)?

    Ans: The minimum value in the array.

  14. Write the method closestPair that prints the two integers in the array arr with the smallest absolute value of the difference.

    public static void closestPair(int[] arr) 
    {
      ...
    }
    	

    For example, if the array arr is {5,8,1,13,7,11} the method should print

     Smallest difference: 1
     Closest pair: 7 8	  
    	

    Hint: Sort the array. (You can use the Arrays.sort method)

    Ans:

    public static void closestPair(int[] arr) 
    {
      if (arr.length < 2) {
        System.out.println("closestPair requires array length >= 2");
        System.exit(0);
      }
    
      Arrays.sort(arr);
      int c1 = arr[0];
      int c2 = arr[1];
    
      int minDist = arr[1] - arr[0];
      for(int i = 1; i < arr.length - 1; i++) {
        int d = arr[i + 1] - arr[i];
        if (d < minDist) {
          minDist = d;
          c1 = arr[i];
          c2 = arr[i + 1];
        }
      }
      System.out.printf("Smallest difference: %d\n", minDist);
      System.out.printf("Closest pair: %d %d\n", c1, c2);
    }
    
  15. What is printed?

    	   String date = "4/25/2013";
    	   String[] f = date.split("/");
    	   int x = Integer.parseInt(f[0]);
    	   int y = Integer.parseInt(f[1]);
    	   int z = Integer.parseInt(f[2]);
    
    	   System.out.printf("%d-%d-%d\n", z, x, y);
    	 

    Ans:

    	   2013-4-25
    	 
  16. Write the print method below to print each element of the Stack on a separate line. This method should NOT use the stack pop method and should not use a 'for each' loop.

    	   public void print(Stack<String> s)
    	   {
    
    	   }
    	 

    Hint: Use the Stack iterator() to get an Iterator<String> and then use the Iterator.

    Ans:

    public void print(Stack<String> s)
    {
      Iterator<String> p = s.iterator();
      
      while(p.hasNext()) {
        System.out.println(p.next());
      }
    }
    
  17. Repeat the previous problem, but use a 'for each' loop.

    Ans:

    public void print(Stack<String> s)
    {
      for(String str: s) {
        System.out.println(str);
      }
    }
    
  18. 1.3.3, 1.3.13, 1.3.18, 1.3.22, 1.3.23, 1.3.24, 1.3.25

    1.3.3 Ans:

    If n is output, all values printed after n that are smaller than n must be in decreasing order.

    So the choices that are not possible are: b, f, and g

    1.3.13 Ans: The values are inserted in order 0, 1, 2, ..., 9. Since the Queue will remove values First In, First Out, the only possible order is a. 0 1 2 3 4 5 6 7 8 9

    1.3.18 Ans: x.next = x.next.next; Deletes the Node after x unless x is the last Node. In case x is the last Node, this would throw a NullPointerException.

    1.3.22 Ans:

    	  t.next = x.next;
    	  x.next = t;
    	

    Inserts the Node t immediately after Node x.

    1.3.23 Ans:

    	  x.next = t;
    	  t.next = x.next;
    	

    The first assignment "loses" all the Nodes that came after x and makes t be the only Node after x. That is, x.next was the only reference to the beginning of those Nodes.

    Then the second statement will make the next member of t reference t itself. So although t is the now the only Node after x, its next member is not null.

    1.3.24 Ans:

    public void removeAfter(Node p)
    {
      if (p == null || p.next == null) {
        return;
      }
    
      p.next = p.next.next;
    
      /** or equivalently using another Node variable for the next Node
    
      Node q = p.next;
      p.next = q.next;
    
      */
    }
    

    1.3.25 Ans:

    public void insertAfter(Node p, Node t)
    {
      if (p == null || t == null) {
        return;
      }
    
      t.next = p.next;
      p.next = t;
    }
    
  19. Suppose the Queue q declared by

    	  Queue<String> s;
    	

    contains 10 Strings. Write code to print the last String and then the next to last String in the Queue s.

    Do not remove any elements from the Queue.

    Ans:

    public void printLast2(Queue<String> q) 
    {
      Stack<String> s = new Stack<String>();
      Iterator<String> p;
    
      p = q.iterator();
    
      while(p.hasNext()) {
        s.push(p.next());
      }
    
      System.out.println(s.pop());
      System.out.println(s.pop());
    
    }
    

    or

    public void printLast2(Queue<String> q)
    {
      Iterator<String> p = q.iterator();
      int n = q.size();
    
      while(n > 2) {
        String str = p.next();
        n--;
      }
      String next2last = p.next();
      String last = p.next();
      System.out.println(last);
      System.out.println(next2last);
    }