-4

I have created a stack .

public class STK {
    static int capacity = 0; 

    STK(int size) {
        capacity = size;
    }

    int stackk[] = new int[capacity];
    int top = 0;

    public void push(int d) {
        if(top < capacity) {
            stackk[top] = d;
            top++;
        } else {
            System.out.println("Overflow");
        }
    } 
}

its implementation

public class BasicStackImplementation {
    public static void main(String[] args) {
        STK mystack = new STK(5);

        mystack.push(51);
        mystack.push(23);
    }
}

when i try to run this code it gives an error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at STK.push(STK.java:21)
    at BasicStackImplementation.main(BasicStackImplementation.java:6)
2
  • You made the array size 0 so you cannot put anything into it. int stackk[] = new int[capacity]; gets executed before you run your constructor method and at that time capacity is 0. Commented Jan 16, 2018 at 20:43
  • 1
    Possible duplicate of [JAVA]Array java.lang.ArrayIndexOutOfBoundsException: 0 error Commented Jan 16, 2018 at 20:44

2 Answers 2

1

Field initializers run before the constructor. Your code is equivalent to this:

static int capacity = 0;
int stackk[]=new int[capacity];
STK(int size)
{
    capacity=size;
}

So you're initializing an empty array. To fix it, just initialize stackk inside the constructor:

int[] stackk;
STK(int size)
{
    capacity = size;
    stackk = new int[capacity];
}

Also, capacity varies by instance and shouldn't be static.

Sign up to request clarification or add additional context in comments.

1 Comment

Or just don't have the capacity field at all, use stackk.length instead.
0

When you made your class, you initialized your array property in your class to equal capacity which is 0. So your array is initialized with 0 elements.

When you call your constructor and set the capacity value, you need to re-initialize your class array equal to new int[value]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.