Test #1, CS 46A, October 6, 2003

There are 100 points on the test

  1. (20 points) What are the values of each of the following expressions, if s is a String with value "abcd"?
    1. 45 / 10;
    2. MATH.pow(10,3);
    3. s.substring(1,3);
    4. s.charAt(2);

  2. (20 points) Which of the following statements are illegal (and will therefore lead to compiler errors)? Which are legal? Justify your answers.
    1. int i = "234";
    2. double d = 12;
    3. char c = "ch";
    4. System.out.print(1 + MATH.PI);

  3. (10 points) Suppose that a Rectangle has been constructed by
    Rectangle r = new Rectangle(10,20,30,40);
    Where will the lower right corner of r be after execution of the statement r.translate(4,6)?

  4. (10 points) Using the BankAccountclass defined in Chapter 2, what will the balances of account1, account2, and account3 be after execution of the instructions below?
      BankAccount account1 = new BankAccount(100);
      BankAccount account2 = new BankAccount(account1.getBalance());
      BankAccount account3 = account1;
      account1.deposit(50);

  5. (10 points) What instruction(s) will draw a red square that is 100 pixels by 100 pixels whose upper-left corner is at position (20,30) of the graphics context g2? The entire square should be red, and not just the border. You may create as many new objects as you need. You may assume that all necessary classes have been imported.

  6. (10 points) Write a public method combine for the BankAccount class of Chapter 2 that takes a BankAccount as argument. The instruction a1.combine(a2) should transfer all of the money from the account a2 to the account a1, leaving a zero balance in account a2. The method should have no return value.

  7. (10 points) Write a constructor for the Purse class of Chapter 3 that will take a Purse object as parameter, and create a new purse with the same contents as the given purse. Hint: the "dot syntax" can be used to access instance fields of another object of the same class, as in Exercise R2.18, p. 74 of the text.

  8. (10 points) Why should instance fields normally be declared as private?