📢 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 HeapQuestion5 {         public static void main(String[] args) {             PriorityQueue pq = new PriorityQueue();             pq.add("apple");             pq.add("banana");             pq.add("cherry");             System.out.println(pq.peek());             System.out.println(pq.size());             System.out.println(pq.peek());         }     }     What will be the output of this program?
    A apple, 3, apple Correct Answer Incorrect Answer
    B apple, 2, banana Correct Answer Incorrect Answer
    C banana, 3, banana Correct Answer Incorrect Answer
    D apple, 3, banana Correct Answer Incorrect Answer
    E cherry, 3, cherry Correct Answer Incorrect Answer

    Solution

    PriorityQueue for String uses natural ordering (alphabetical) by default, making it a min-heap.     1.  pq.add("apple"); pq.add("banana"); pq.add("cherry");         The elements are added. "apple" is the smallest alphabetically.     2.  System.out.println(pq.peek());         peek() retrieves the head of the queue (the highest-priority element) *without removing it*. So, "apple" is printed.     3.  System.out.println(pq.size());         The size of the queue is still 3, as peek() does not remove elements. So, 3 is printed.     4.  System.out.println(pq.peek());         Again, peek() retrieves the head without removal. "apple" is still the head. So, "apple" is printed.     Therefore, the output is apple, 3, apple.

    Practice Next
    ask-question