Homework: Tracing With References


Answer the following questions. For the tracing exercises, you should be able to complete the tracing tables on this page and then print the page from the browser.

  1. Consult the contract for Standard interface's method transferFrom specified here and then complete the tracing table from slides 78-79 from Meeting 23 reproduced here where m and k are variables of type NaturalNumber.

    Statement Variable Values
    m → 143
    k → 70
    m.transferFrom(k);
    m →
    k →

  2. Explain why an immutable type cannot have a transferFrom method as specified in the Standard interface.

  3. Complete the following tracing tables. Each of them has a short method declaration followed by short client code that invokes the method. Carefully complete each tracing table starting from the client code and tracing over the method call and through the method body.

    1. Swapping for primitive types:

      Statement Variable Values
      private static void swap1(int i1, int i2) {
      i1 =
      i2 =
          int tmp = i1;
      i1 =
      i2 =
      tmp =
          i1 = i2;
      i1 =
      i2 =
      tmp =
          i2 = tmp;
      i1 =
      i2 =
      tmp =
      }
      Start tracing here
      int x = 7, y = 12;
      x =
      y =
      swap1(x, y);
      x =
      y =

    2. Swapping for (immutable) reference types:

      Statement Variable Values
      private static void swap2(String s1, String s2) {
      s1 →
      s2 →
          String tmp = s1;
      s1, tmp →
      s2 →
          s1 = s2;
      s1, s2 →
      tmp →
          s2 = tmp;
      s1 →
      s2, tmp →
      }
      Start tracing here
      String x = "legends", y = "leaders";
      x →
      y →
      swap2(x, y);
      x →
      y →

    3. Swapping for (mutable) reference types:

      Statement Variable Values
      private static void swap3(NaturalNumber n1, NaturalNumber n2) {
      n1 →
      n2 →
          NaturalNumber tmp = n1;
      n1, tmp →
      n2 →
          n1 = n2;
      n1, n2 →
      tmp →
          n2 = tmp;
      n1 →
      n2, tmp →
      }
      Start tracing here
      NaturalNumber x = new NaturalNumber2(41), y = new NaturalNumber2(78);
      x →
      y →
      swap3(x, y);
      x →
      y →