ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Node<T> {
    T value;
    Node<T> next;
    Node(T v) { value = v; }
}
public class Main {
    static <T> int length(Node<T> head) {
        int n = 0;
        while (head != null) { n++; head = head.next; }
        return n;
    }
    public static void main(String[] args) {
        Node<String> a = new Node<>("a");
        Node<String> b = new Node<>("b");
        a.next = b;
        System.out.println(length(a));
    }
}
  1. A. 0
  2. B. 1
  3. C. 2
  4. D. Compile-time error: Node<T> cannot have a field of its own generic type

Correct answer: C. 2

A generic class may freely reference its own type parameter for fields, including a self-referential next : Node<T>, exactly like a non-generic linked list. length() walks from a through b, counting 2 nodes before head becomes null.

More OOP with C++ and Java questions

Exams that ask this topic