how this code is making NullPointerException in push and main: Here is the code:
class Stack {
private char ch[];
private int top;
Stack(int n) {
char ch[] = new char[n];
top = -1;
}
void push(char c) {
if (top == ch.length - 1) {
System.out.println("Stack full.");
return;
}
top++;
ch[top] = c;
}
char pop() {
if (isEmpty()) {
System.out.println("Stack empty");
return (char) 0;
}
char p;
p = ch[top];
top--;
return p;
}
boolean isEmpty() {
if (top == -1)
return true;
else
return false;
}
}
class StackDemo {
public static void main(String args[]) {
final int size = 10;
Stack s = new Stack(size);
// Push charecters into the stack
for (int i = 0; i < size; i++) {
s.push((char) ((int) 'A' + i));
}
// pop the stack untill its empty
for (int i = size - 1; i >= 0; i--) {
System.out.println("Poped element " + i + " is " + s.pop());
}
}
}
The error code generated is :
0Exception in thread "main" java.lang.NullPointerException at Stack.push(StackDemo.java:11) at StackDemo.main(StackDemo.java:46)
Do i have to put these classes in a package as there is already a Stack library in java?