Queue Inspection Methods: element and peek
You'll learn how to look at the front element of a Queue without removing it, and understand when each inspection method throws exceptions versus returns null.
The Need to Look Without Removing
Sometimes you want to see what's next in line without actually taking it out. Imagine peeking through a window at the front of a queue at a ticket counter—you're just looking, not joining or leaving the line. Java's Queue interface provides two methods for this: element() and peek().
The Two Inspection Methods
element() — Returns the head element of the queue without removing it. If the queue is empty, it throws NoSuchElementException. This is the "strict" inspection method.
peek() — Returns the head element of the queue without removing it. If the queue is empty, it returns null. This is the "gentle" inspection method.
Queue<String> queue = new LinkedList<>();
queue.offer("First");
queue.offer("Second");
String head1 = queue.peek(); // "First", queue unchanged
String head2 = queue.element(); // "First", queue unchanged
// Queue still contains: "First", "Second"
queue.poll(); // Remove "First"
queue.poll(); // Remove "Second"
String result = queue.peek(); // null (empty queue, no exception)
// String oops = queue.element(); // Throws NoSuchElementException!
When to Use Which
Use peek() when an empty queue is a normal, expected situation—your code can handle null gracefully. Use element() when an empty queue indicates a programming error that should crash immediately.
Key Takeaway: element() and peek() both inspect the queue's head without removal; element() throws an exception on empty queues while peek() returns null, mirroring the exception-vs-null pattern of remove() vs poll().