TheAlgorithms/Java · error · IllegalArgumentException

Stack size must be greater than 0

Error message

Stack size must be greater than 0

What it means

Thrown by the StackArray(int size) constructor when size is zero or negative. The constructor allocates an Object[] of the given length and sets top=-1; a non-positive size would create an invalid (zero-length or failing) backing array. The IllegalArgumentException rejects this at construction time rather than failing later on push.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java:39

    /**
     * Creates a stack with a default capacity.
     */
    @SuppressWarnings("unchecked")
    public StackArray() {
        this(DEFAULT_CAPACITY);
    }

    /**
     * Creates a stack with a specified initial capacity.
     *
     * @param size the initial capacity of the stack, must be greater than 0
     * @throws IllegalArgumentException if size is less than or equal to 0
     */
    @SuppressWarnings("unchecked")
    public StackArray(int size) {
        if (size <= 0) {
            throw new IllegalArgumentException("Stack size must be greater than 0");
        }
        this.maxSize = size;
        this.stackArray = (T[]) new Object[size];
        this.top = -1;
    }

    /**
     * Pushes an element onto the top of the stack. Resizes the stack if it is full.
     *
     * @param value the element to push
     */
    @Override
    public void push(T value) {
        if (isFull()) {
            resize(maxSize * 2);
        }
        stackArray[++top] = value;
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a strictly positive capacity; use the no-arg constructor if you want the DEFAULT_CAPACITY.
  2. Clamp computed sizes to at least 1 before constructing: Math.max(1, computedSize).
  3. Validate external input (config/UI/API) before it reaches the constructor.
  4. Prefer StackArray() (default capacity) when you have no specific size requirement.

Example fix

// before
StackArray<String> s = new StackArray<>(inputCapacity);
// after
int cap = Math.max(1, inputCapacity);
StackArray<String> s = new StackArray<>(cap);
Defensive patterns

Strategy: validation

Validate before calling

int cap = Math.max(1, requestedSize);
StackArray<T> s = new StackArray<>(cap);

Prevention

When it happens

Trigger: Constructing StackArray with a literal 0 or negative number. Passing a capacity derived from user input or config without clamping to a minimum. Passing a computed size (e.g., collection.size() on an empty collection) that evaluates to 0.

Common situations: Configuration files where a capacity property is left blank or set to 0. Capacity derived from request payload sizes that can legitimately be zero. Default-value bugs where a constant is mis-set.

Related errors


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