TheAlgorithms/Java · error · IllegalStateException

Queue is empty, cannot peek rear

Error message

Queue is empty, cannot peek rear

What it means

Thrown by Queue.peekRear() as an IllegalStateException when isEmpty(). The method returns queueArray[rear] without removing it; with nItems == 0 the rear index points at no valid element. Read-only underflow guard, symmetric to peekFront.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/queues/Queue.java:101

     */
    @SuppressWarnings("unchecked")
    public T peekFront() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty, cannot peek front");
        }
        return (T) queueArray[front];
    }

    /**
     * Checks the element at the rear of the queue without removing it.
     *
     * @return Element at the rear of the queue.
     * @throws IllegalStateException if the queue is empty.
     */
    @SuppressWarnings("unchecked")
    public T peekRear() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty, cannot peek rear");
        }
        return (T) queueArray[rear];
    }

    /**
     * Returns true if the queue is empty.
     *
     * @return True if the queue is empty.
     */
    public boolean isEmpty() {
        return nItems == 0;
    }

    /**
     * Returns true if the queue is full.
     *
     * @return True if the queue is full.
     */

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard with isEmpty() before peekRear() and return null/Optional when empty.
  2. Ensure at least one insert() precedes the first peekRear().
  3. Catch IllegalStateException when emptiness is an expected branch.

Example fix

// before
T tail = queue.peekRear(); // throws when empty

// after
T tail = queue.isEmpty() ? null : queue.peekRear();
Defensive patterns

Strategy: validation

Validate before calling

T tail = queue.isEmpty() ? null : queue.peekRear();

Type guard

null

Try / catch

null

Prevention

When it happens

Trigger: Calling peekRear() before any insert(), or after the queue has been fully drained. Reading the rear of an empty ring buffer throws.

Common situations: Checking the last-inserted item for batching/coalescing before the producer has sent data; verifying insert order in tests without seeding; logging the tail element on an empty queue.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/229cb4c808fe733e. Report an issue: GitHub.