📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider a Java method printList(Node head) for a singly

    linked list. class Node {     int data;     Node next;     Node(int d) { data = d; next = null; } } public void printList(Node head) {     Node current = head;     while (current != null) {         System.out.print(current.data + " ");         current = current.next;     }     // Bug: What if the list is empty?     System.out.println(current.data); // Line X } If printList(null) is called (an empty list), what will happen at Line X?
    A The program will print nothing and terminate normally. Correct Answer Incorrect Answer
    B A NullPointerException will be thrown. Correct Answer Incorrect Answer
    C It will print 0 (default value for int). Correct Answer Incorrect Answer
    D It will print null. Correct Answer Incorrect Answer
    E It will print an empty string. Correct Answer Incorrect Answer

    Solution

    • Dry Run: o Call printList(null):  head is null.  Node current = head; sets current to null.  The while (current != null) condition (null != null) is false. The loop is skipped entirely.  Execution proceeds to System.out.println(current.data); (Line X).  At this point, current is null. Attempting to access current.data on a null reference triggers a NullPointerException. • Why Correct Answer (B): A NullPointerException will be thrown. o This directly follows from the dry run. The code attempts to dereference a null pointer after the loop.

    Practice Next
    ask-question