Java - Queue Overview-interview
Q1. What is a Queue in Java?
A Queue in Java is a data structure that follows the FIFO (First-In, First-Out) principle. It is an interface in the Java Collections Framework (java.util.Queue) used to hold elements before processing.
Q2. What are the main implementations of Queue in Java?
- LinkedList → Implements Queue, Deque.
- PriorityQueue → Orders elements based on priority.
- ArrayDeque → Resizable array implementation of Deque.
- ConcurrentLinkedQueue → Thread-safe queue for concurrent environments.
Q3. What are the main methods of the Queue interface?
- add() → Inserts element, throws exception if full.
- offer() → Inserts element, returns false if full.
- remove() → Removes head element, throws exception if empty.
- poll() → Removes head element, returns null if empty.
- peek() → Retrieves head without removing, null if empty.
- element() → Retrieves head, throws exception if empty.
Q4. When would you use a PriorityQueue in Java?
A PriorityQueue is used when elements must be processed according to priority rather than insertion order (e.g., task scheduling, job processing).
Q5. Difference between Queue and Stack in Java?
- Queue → Follows FIFO (First In, First Out).
- Stack → Follows LIFO (Last In, First Out).