Course contentsShow
← Java
Lesson 1197 of 2,87027. Queue and Deque ImplementationsFree lesson

Peek Operations: peekFirst and peekLast

Examining elements at both ends of the deque without removal, returning null if deque is empty.

Peek Operations: peekFirst and peekLast

You'll learn how to safely inspect elements at both ends of a deque without modifying it.

What Does "Peek" Mean?

When you peek at a deque, you're looking at an element without removing it — like glancing at the first or last person in line without asking them to leave. The Deque interface provides two methods for this: peekFirst() examines the front element, and peekLast() examines the rear element.

How Peek Operations Work

Both methods return the element they find, but if the deque is empty, they return null instead of throwing an exception. This makes them safer than getFirst() and getLast(), which throw NoSuchElementException on empty deques.

Think of it like checking if anyone is waiting in line before trying to talk to them — you get a clear "no one's there" signal (null) rather than an error.

When to Use Peek Operations

Use peekFirst() and peekLast() when you need to:

  • Check what's at either end without removing it
  • Avoid exceptions when the deque might be empty
  • Make decisions based on boundary elements before processing

For example, you might peek at the last element to decide whether to add a new one, or peek at the first element to see if it's ready for processing without actually removing it yet.

The Safety Advantage

Unlike their exception-throwing cousins (getFirst() and getLast()), peek operations let you safely check emptiness and contents in one operation. If you get null back, you know the deque is empty.

Key Takeaway: peekFirst() and peekLast() let you examine elements at both ends of a deque without removal, returning null for empty deques instead of throwing exceptions — making them ideal for safe inspection operations.