CS 61B: Data Structures (Spring 2009)
Midterm I


Problem 1. (7 points) Quickies.

a. Each object has its own distinct copy of an instance variable. But all the objects in a class share just one “copy” of a class variable.

b. No. The super keyword calls a superclass method on this. But in a static method, there is no this.

c. The program prints “The number is 8”. The reset method, via the increment method, successfully increments the n field in the original What object from 7 to 8. Then the reset method creates a new What object and sets its n field to zero. But main passed the reference w by value. When reset changes its local variable w, the local variable w in main still references the original object, which still holds an 8 in its field n.

Again, the key is that w was passed by value.

d. This code goes into an infinite loop in which the constructor keeps calling itself recursively. (Eventually, the Java Virtual Machine runs out of stack space and throws an exception.) We thank the many students in the class who inspired this question by doing this in their assignments.

Problem 2. (8 points) Inheritance.

A few of the blanks have more than one correct answer. Here's one possible solution.

import java.io.*;

interface Aaa {
  public double number();

abstract class Bbb {
  public int[][] i;

  public Bbb(int j) {
    i = new int[4][6];
    i[3][5] = j;

  public double number() {
    return 12.73;

  public abstract void cureCancer();

public class Ccc extends Bbb implements Aaa {
  public Ccc() {

  public void cureCancer(int i) {
    this.i[1][1] = 4;

  public void cureCancer() {

  public static void main(String[] args) {
    Aaa a = new Ccc();
    Bbb b = (Bbb) a;
    b.i[0][0] = 1;
Problem 3. (10 points) Removing a Node from a List.


  public void removeNode(SListNode node) {
    if (head == node) {
      head = head.next;
    } else {
      SListNode n = head;
      while (n.next != node) {
        n = n.next;
      n.next = n.next.next;

  public void removeNode(SListNode node) {
    DListNode dnode = (DListNode) node;  // Assume this cast always succeeds.
    if (tail == node) {
      tail = dnode.prev;
    } else {
      ((DListNode) node.next).prev = dnode.prev;

Mail inquiries to cs61b@cory.eecs