How to I incorporate NullPointerException in the following push() method for a stack in Java?
public void push(E e) {
int len = size();
if (len == 0)
throw new NullPointerException();
else
addElement(e);
System.out.println("The element pushed is " + e);
}
In the PSVM, whenever I call the push() method it gives out the NullPointerException without adding to the stack.
public static void main(String[] args) {
try {
SortableStack<Object> s = new SortableStack<Object>();
s.push(10);
s.push(20);
System.out.println("The element popped is " + s.pop());
}
catch (NullPointerException e) {
System.out.println("Null Pointer Exception encountered!");
}
}
I am not %100 sure what you want to achieve, but you should check for
null-ness ofe, not the size of the stack: