TheAlgorithms/Java · error · IllegalArgumentException

Queue capacity must be greater than 0

Error message

Queue capacity must be greater than 0

What it means

Thrown by the Queue(int capacity) constructor as an IllegalArgumentException when capacity <= 0. The array-backed queue allocates queueArray = new Object[capacity] immediately, so a non-positive capacity is impossible to allocate and is rejected up front.

Source

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

    private int rear;
    private int nItems;

    /**
     * Initializes a queue with a default capacity.
     */
    public Queue() {
        this(DEFAULT_CAPACITY);
    }

    /**
     * Constructor to initialize a queue with a specified capacity.
     *
     * @param capacity The initial size of the queue.
     * @throws IllegalArgumentException if the capacity is less than or equal to zero.
     */
    public Queue(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("Queue capacity must be greater than 0");
        }
        this.maxSize = capacity;
        this.queueArray = new Object[capacity];
        this.front = 0;
        this.rear = -1;
        this.nItems = 0;
    }

    /**
     * Inserts an element at the rear of the queue.
     *
     * @param element Element to be added.
     * @return True if the element was added successfully, false if the queue is full.
     */
    public boolean insert(T element) {
        if (isFull()) {
            return false;
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate capacity > 0 before construction and fall back to a sane default (e.g. the no-arg Queue() which uses DEFAULT_CAPACITY).
  2. Clamp computed capacities: Math.max(1, computed).
  3. Treat a zero/negative capacity from config as a fatal misconfiguration and fail startup with a clear message.

Example fix

// before
Queue<T> q = new Queue<>(configuredCapacity); // may be <= 0

// after
int cap = Math.max(1, configuredCapacity);
Queue<T> q = new Queue<>(cap);
Defensive patterns

Strategy: validation

Validate before calling

int cap = Math.max(1, configuredCapacity);
Queue<T> q = new Queue<>(cap);

Type guard

boolean validCapacity = configuredCapacity > 0;

Try / catch

null

Prevention

When it happens

Trigger: Passing 0 or a negative number to new Queue<>(capacity); passing a computed capacity (e.g. from config, a list size, or a formula) that evaluates to zero or below under some input.

Common situations: Config value for queue size left blank/zero; capacity derived as (someCount - buffer) that goes negative when input is small; deserialized/defaulted settings producing 0; copy-paste of a default constant that was never set.

Related errors


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