TheAlgorithms/Java · error · IllegalArgumentException

Size must be greater than 0

Error message

Size must be greater than 0

What it means

Thrown by the CircularQueue constructor when size < 1. The queue allocates an Object[] of length `size`, so a zero or negative size would create a degenerate array. The library requires at least one slot to be a meaningful FIFO buffer.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java:41

 * @param <T> the type of elements in this queue
 */
public class CircularQueue<T> {
    private T[] array;
    private int topOfQueue;
    private int beginningOfQueue;
    private final int size;
    private int currentSize;

    /**
     * Constructs a CircularQueue with a specified capacity.
     *
     * @param size the maximum number of elements this queue can hold
     * @throws IllegalArgumentException if the size is less than 1
     */
    @SuppressWarnings("unchecked")
    public CircularQueue(int size) {
        if (size < 1) {
            throw new IllegalArgumentException("Size must be greater than 0");
        }
        this.array = (T[]) new Object[size];
        this.topOfQueue = -1;
        this.beginningOfQueue = -1;
        this.size = size;
        this.currentSize = 0;
    }

    /**
     * Checks if the queue is empty.
     *
     * @return {@code true} if the queue is empty; {@code false} otherwise
     */
    public boolean isEmpty() {
        return currentSize == 0;
    }

    /**

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate `size >= 1` before constructing, and apply a sensible minimum.
  2. Provide a non-zero default in config when the value is missing.
  3. Clamp computed sizes to at least 1.
  4. Fail the configuration load early with a clear message rather than reaching the constructor.

Example fix

// before
CircularQueue<T> q = new CircularQueue<>(configuredSize);

// after
int size = Math.max(1, configuredSize);
CircularQueue<T> q = new CircularQueue<>(size);
Defensive patterns

Strategy: validation

Validate before calling

int capacity = Math.max(1, configuredSize);
new CircularQueue<T>(capacity);

Try / catch

try {
    new CircularQueue<T>(size);
} catch (IllegalArgumentException e) {
    new CircularQueue<T>(1);
}

Prevention

When it happens

Trigger: Constructing CircularQueue(0) or CircularQueue(-1). Sizing the queue from a config value or computation that yields zero or negative. Sizing from a count of available items when none are available.

Common situations: Capacity read from a properties file defaulting to 0. Size computed as `max(a - b, 0)` when a <= b. Environment where the configured buffer size was not set and parsed as 0.

Related errors


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