-1

In the following java program, I am trying to implement a stack using array

class stack{
    int size, top;
    int arr[];

    stack(int n){
        size = n;
        top = -1;
        int arr[] = new int[size];
    }

    void push(int x){
        ++top;
        if(top >= size){
            System.out.println("Stack overflow");
            top = size-1;
        }
        else{
            System.out.println("Data pushed: "+x);
            arr[top] = x;
        }
        return;
    }

    void pop(){
        if(top < 0){
            System.out.println("Stack Underflow");
        }
        else{
            System.out.println("Data popped: "+arr[top]);
            --top;
        }
        return;
    }
}

public class test{
    public static void main(String[] args){
        stack S = new stack(3);
        S.push(5);
        S.push(6);
        S.push(7);
        S.push(8);
        S.pop();
        S.pop();
        S.pop();
        S.pop();
    }
}

After the first "push" operation the program throws the error: Exception in thread "main" java.lang.NullPointerException .

I tried initializing the array out of the constructor and it solves the problem, so I wanted to know what is wrong with the approach given above?

class stack{
    int size, top;
    int arr[] = new int[100];

    stack(int n){
        size = n;
        top = -1;
        //int arr[] = new int[size];
    }
  • 1
    Replace ```int arr[] = new int[size];``` with ```arr = new int[size]``` in your constructor – zysaaa Mar 24 '22 at 12:15

2 Answers2

1
int size, top;
int arr[];

stack(int n){
    size = n;
    top = -1;
    int arr[] = new int[size]; // these creates a local variable arr
}

Your problem here is that you are not instantiating your instance member, but creating a second, local array.

int size, top;
int arr[];

stack(int n){
    size = n;
    top = -1;
    arr = new int[size]; // Don't redeclare arr, but use the existing one
}

This should fix the issue.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

 stack(int n){
        size = n;
        top = -1;
        int arr[] = new int[size];
    }

In the constructor , you are creating a new local variable arr[]. The instance variable is still uninitialised. And by default, the value given to it is null. Hence when you are trying to call an action on it, it is throwing Null Pointer Exception

Try this:

stack(int n){
        size = n;
        top = -1;
        arr[] = new int[size];
    }

For better understanding of variable scoping refer to this :https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.3