CSCI A202 - Introduction to Programming (II)

Final Exam Information

Sample Problem 3

Consider the following class:

class Pair {
  Pair first; 
  Pair second; 
  Pair(Pair f, Pair s) { first = f; second = s; } 
  public static void main(String[] args) {
    Pair p = new Pair(null, null); 
    Pair q = new Pair(null, null); 
    Pair r = new Pair(p, q); 
    System.out.println(r.function()); 
  } 
  int function() { 
    int left, right; 
    if (first == null) { left = 0; } 
    else { left = first.function(); }
    if (second == null) { right = 0; } 
    else { right = second.function(); }
    return 1 + left + right; 
  }   
}
The first three lines of method main create three objects and using intermediate variables p and q eventually assign a Pair object to r. Draw a diagram that describes the structure to which r points after the third assignment.
 


What will be the output of this program when you compile it and run it?

0
1
2
3
4
Briefly justify your answer below.

 


What is a good name for the instance method function? What does it compute? What would the result be if we were to invoke p.function() instead of r.function() in the last line of main?
 


Suppose we add a new line
Pair b = new Pair(); 
at the beginning of method main. Does the program still compile? Why?