Queue (I) Overview in Java

Java Queue is an interface that extends the Collection interface. It represents a collection of elements in which insertion and removal of elements occur at opposite ends (i.e., one end for adding elements, and the other end for removing elements). In other words, a Queue follows the First-In-First-Out (FIFO) principle, where the first element that is inserted will be the first element to be removed.

The Queue interface declares several methods, such as:

1. add(element): adds an element to the queue, returns a boolean indicating whether the operation was successful or not.

2. offer(element): adds an element to the queue, returns true if successful or false otherwise.

3. remove(): removes the head element of the queue and returns it. Throws NoSuchElementException if the queue is empty.

4. poll(): removes and returns the head element of the queue or returns null if the queue is empty.

5. element(): returns the head element of the queue without removing it. Throws NoSuchElementException if the queue is empty.

6. peek(): returns the head element of the queue without removing it, or returns null if the queue is empty.

Here's an example of how to use the Queue interface:
                
    import java.util.*;

    public class QueueExample {
        public static void main(String[] args) {
            Queue<String> queue = new LinkedList<>();

            // Adding elements to the queue
            queue.add("A");
            queue.add("B");
            queue.add("C");

            // Printing the elements in the queue
            System.out.println("Queue: " + queue);

            // Removing the head element from the queue
            String removed = queue.remove();
            System.out.println("Removed element: " + removed);

            // Printing the elements in the queue after removal
            System.out.println("Queue after removal: " + queue);

            // Adding an element to the queue
            queue.offer("D");
            System.out.println("Queue after offer: " + queue);

            // Printing the head element of the queue without removing it
            String peeked = queue.peek();
            System.out.println("Peeked element: " + peeked);
        }
    }
                
            

The output of the program would be:

                
    Queue: [A, B, C]
    Removed element: A
    Queue after removal: [B, C]
    Queue after offer: [B, C, D]
    Peeked element: B
                
            

In addition to the LinkedList implementation used in the example, there are other implementation classes available in Java, such as PriorityQueue and ArrayDeque, that implement the Queue interface with different performance characteristics and tradeoffs.