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
apoints after the assignment.
What will be the output of this program when you compile it and run it?
Briefly justify your answer below.
What is a good name for the instance method function?
Suppose we add a new line
at the beginning of methodLink b = new Link();
main. Does the program still
compile? Why?