Which is a type of Queue?

Java MCQ: Which is a type of Queue?

A) Priority Queue
B) LIFO Queue
C) FILO Queue
D) None of the above

Answer:

A) Priority Queue

Explanation:

A priority queue is a type of queue where each element is associated with a priority. Elements with higher priority are dequeued before elements with lower priority, regardless of their order in the queue. If two elements have the same priority, they are dequeued according to the FIFO principle.

Priority queues are commonly used in scenarios where certain tasks or data must be processed before others, such as in operating systems for managing processes, in networking for handling packets, and in algorithms like Dijkstra’s shortest path algorithm.

Here’s an example of a priority queue in Java:


import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(30);
        pq.add(10);
        pq.add(20);
        System.out.println(pq.poll()); // Outputs: 10 (smallest element dequeued first)
        System.out.println(pq); // Outputs: [20, 30]
    }
}

In this example, the priority queue orders elements in ascending order by default, with the smallest element (10) having the highest priority. Understanding the concept of a priority queue is crucial for implementing systems where prioritization of tasks or data is necessary.

Reference links:

https://www.javaguides.net/p/java-priority-queue-tutorial.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top