Search code examples
javastack

Even though the Stack is empty why does it throws error saying "Stack is full" whenever I want to push element?


I have created 2 classes, one is a generic class ArrayStack<E> that has all the methods of a stack [i.e. push(), pop(), top(), isEmpty(), size()] and all these methods are implemented on an array (public E arr[];).This is the constructor which is a part of this class :

    public ArrayStack(int capacity) {
    arr = (E[]) new Object[capacity];
}

This is the Size() method of above mentioned class :

    private int t = -1;
    public int size() {
    return t + 1;
    }

This is the push() method:

    public void push(E element) throws IllegalStateException {
    if (size() == arr.length) {
        throw new IllegalStateException("Stack is full");
    }
    arr[++t] = element;
}

Another class is class dec_to_bin which converts decimal to binary which uses the methods of ArrayStack class. Since dec_to_bin class uses methods of previous class I have created object of ArrayStack class in this class ArrayStack<Long> a1=new ArrayStack<Long>(32);

After converting decimal to binary I am pushing those 1/0s onto the stack but it gives below error

    Exception in thread "main" java.lang.IllegalStateException: Stack is full
    at ArrayStack.push(test.java:36)
    at dec_to_bin.pushing(test.java:64)
    at dec_to_bin.process(test.java:75)
    at test.main(test.java:115)

pushing(): it is the method that converts dec to binary and pushes onto the stack. You can refer below Pastebin link: https://pastebin.com/CNahygvC


Solution

  • First of all this line of code return t + 1; is very bad to the program, if you give it t = 0 it will return 1, which makes no sense. The problem you are observing comes from this if statement.

        public void push(E element) throws IllegalStateException {
            if (size() == arr.length) {
                throw new IllegalStateException("Stack is full");
            }
            // size++;
            arr[++t] = element;
        }
    

    Because if you notice size() and length() are now almost always giving the exact same output. Meaning that because they will almost always give the same output(0 is the exception) that then they will almost always be equal, therefore the error. Hope this helps.