CSCI A202 - Introduction to Programming (II)

Final Exam Information

Sample Problem 2

Consider the following class:

class Link {
  int value; 
  Link next;
  Link (int v, Link n) { value= v; next = n; } 
  public static void main(String[] args) {
    Link a = new Link(2, new Link(2, new Link(2, null))); 
    System.out.println(a.function()); 
  } 
  int function() {
    if (next == null) { return 1; } 
    else { return 1 + next.function(); } 
  } 
}
The first line of method main creates a new Link object and assigns it to the variable a.
How many objects are being created in the process?

Draw a diagram that describes the structure to which a points after the 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?
 


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