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


    Question

    Consider the following Java code snippet:    

    import java.util.PriorityQueue;     import java.util.Comparator;     class Item {         int priority;         String name;         public Item(int priority, String name) {             this.priority = priority;             this.name = name;         }         @Override         public String toString() {             return name + "(" + priority + ")";         }     }     public class HeapQuestion7 {         public static void main(String[] args) {             // Create a min-heap based on 'priority'             PriorityQueue pq = new PriorityQueue(Comparator.comparingInt(item -> item.priority));             pq.add(new Item(5, "Task A"));             pq.add(new Item(1, "Task B"));             pq.add(new Item(10, "Task C"));             pq.add(new Item(3, "Task D"));             System.out.println(pq.poll().name);             System.out.println(pq.poll().name);         }     }     What will be the output of this program?
    A Task A, Task B Correct Answer Incorrect Answer
    B Task B, Task D Correct Answer Incorrect Answer
    C Task B, Task A Correct Answer Incorrect Answer
    D Task C, Task A Correct Answer Incorrect Answer
    E Task D, Task A Correct Answer Incorrect Answer

    Solution

    The PriorityQueue is initialized with a Comparator that orders Item objects based on their priority field in ascending order (min-heap behavior for priority).     1.  pq.add(new Item(5, "Task A"));     2.  pq.add(new Item(1, "Task B"));     3.  pq.add(new Item(10, "Task C"));     4.  pq.add(new Item(3, "Task D"));         After these additions, the item with the lowest priority value will be at the head of the queue. The priorities are 1, 3, 5, 10.     5.  System.out.println(pq.poll().name);         The item with priority 1 ("Task B") is removed and its name is printed.     6.  System.out.println(pq.poll().name);         The next item with the lowest priority (from the remaining items) is the one with priority 3 ("Task D"). It is removed and its name is printed.     Therefore, the output is Task B, Task D.

    Practice Next
    ask-question