📢 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;     public class HeapQuestion1 {         public static void main(String[] args) {             PriorityQueue minHeap = new PriorityQueue();             minHeap.add(10);             minHeap.add(5);             minHeap.add(20);             minHeap.add(3);             minHeap.add(15);             System.out.println(minHeap.poll());             System.out.println(minHeap.peek());             System.out.println(minHeap.poll());         }     }     What will be the output of this program?
    A 3, 5, 5 Correct Answer Incorrect Answer
    B 3, 5, 10 Correct Answer Incorrect Answer
    C 5, 3, 10 Correct Answer Incorrect Answer
    D 3, 10, 5 Correct Answer Incorrect Answer
    E 10, 5, 20 Correct Answer Incorrect Answer

    Solution

    A PriorityQueue in Java is by default a min-heap, meaning the smallest element has the highest priority.     1.  minHeap.add(10); minHeap.add(5); minHeap.add(20); minHeap.add(3); minHeap.add(15);         After these additions, the heap contains {3, 5, 10, 15, 20} (not necessarily in this order internally, but 3 is at the root).     2.  System.out.println(minHeap.poll());         poll() removes and returns the smallest element. So, 3 is removed and printed. The heap now contains {5, 10, 15, 20}.     3.  System.out.println(minHeap.peek());         peek() retrieves the smallest element *without removing it*. The smallest element is now 5. So, 5 is printed. The heap still contains {5, 10, 15, 20}.     4.  System.out.println(minHeap.poll());         poll() removes and returns the smallest element again. So, 5 is removed and printed. The heap now contains {10, 15, 20}.     Therefore, the output is 3, 5, 5.

    Practice Next
    More IT Operating System Questions
    ask-question