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];
}