CS101 Lab 3: Solutions to Part I

Ask if you are surprised by any of these answers.
  1. Alice has $125.00
    Bob can withdraw $125.00? false
    Bob can withdraw $25.00? true
    Bob has $75.00
    Charlie can withdraw $25.00? true
    Charlie has $100.00
    Alice has $100.00
    After transfer...
    Charlie has $100.00
    Alice has $100.00

  2. Cumulative account reference variables created...
    after line 1: 2
    after line 2: 2
    after line 3: 2
    after line 5: 2
    after line 9: 3

  3. Cumulative account objects created...
    after line 1: 0
    after line 2: 1
    after line 3: 1
    after line 5: 2
    after line 9: 2

  4. This account has $60.00
    would be printed. The expression (new Account(60)) evaluates to an account object reference, and the toString method is then called on that object.

  5. The Account object becomes inaccessible (garbage) immediately after the line is executed, since there is no reference variable that refers to it. Therefore, subsequent lines of code would not have any way to use the object.

  6. The error is that foo has not been initialized before line 2, so execution would result in a null pointer exception. (In this case, the compiler may complain that foo has not been initialized. To correct the problem, one could create an account object, for example by adding the line
    foo = new Account(50);
    after line 1. (Alternatively, one could replace line 1 by
    Account foo = new Account(50);
    to correct the error.)