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?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.