Quiz, Data Structures and Algorithms, Week 10 -- Thurs Nov 29 2001

Name:

Assume the following Java code:


class Thing {

    // Instance variables

    Thing next;

    int i;

    String s;



    // Constructor

    public Thing(int x, String msg) { i = x; s = msg; next = null; }

}



public class ThingDemo {

    public static void main(String argv[]) {

        Thing thing1 = null, thing2 = null;

	Thing list = null, temp = null, ref = null;

        // code appears in numbered problems below ...

    }

}

Assume the code fragments in the numbered problems below are executed in the main method in the order they appear. The questions in each problem refer to the program state after the fragment executes (and before the next fragement executes).

  1. 
    thing1 = new Thing(99, "Hi");
    
    thing2 = thing1;
    
    
    a. How many Thing objects are there?

    Write the value of each of the following expressions:
    b.  thing1.i c.  thing1.s d.  thing2.i e.  thing2.s
    f.  thing1.i == thing2.i g.  thing1.s == thing2.s
    h.  thing1 == thing2


  2. 
    thing2.s = "Bye";
    
    
    Write the value of each of the following expressions:
    a.  thing1.s b.  thing2.s c.  thing1 == thing2


  3. 
    thing2 = new Thing(99, "Bye");
    
    
    a. How many Thing objects are there?

    Write the value of each of the following expressions:
    b.  thing1.s c.  thing2.s d.  thing1 == thing2


  4. 
    thing2.s = "Foo";
    
    
    Write the value of each of the following expressions:
    a.  thing1.s b.  thing2.s c.  thing1 == thing2


  5. 
    list = new Thing(1, "A");
    
    temp = new Thing(2, "B");
    
    temp.next = list;
    
    list = temp;
    
    
    Write the value of each of the following expressions:
    a.  list.i b.  list.s c.  list.next.i c.  list.next.s


  6. 
    temp = new Thing(3, "C");
    
    temp.next = list;
    
    list = temp;
    
    
    
    System.out.print("list");
    
    for (ref = list; ref != null; ref = ref.next) {
    
        System.out.print(" -> " + ref.s);
    
    }
    
    System.out.println(".");
    
    
    1. Write the output that this fragment prints.


    2. Write a single Java statement (with no loops) that prints the value of the instance variable i in the object at the tail of the list.