-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)
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
Mridul Mittal
  • 51
  • 1
  • 6
  • 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. – takendarkk Jan 16 '18 at 20:43
  • 1
    Possible duplicate of [\[JAVA\]Array java.lang.ArrayIndexOutOfBoundsException: 0 error](https://stackoverflow.com/questions/36244469/javaarray-java-lang-arrayindexoutofboundsexception-0-error) – Tom Jan 16 '18 at 20:44

2 Answers2

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138
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]

Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40