Q:

NullPointerException in push() method of Stack in Java

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!");
        }
}

A:

I am not %100 sure what you want to achieve, but you should check for null-ness of e, not the size of the stack:
public void push(E e) {
    if (e == null) {
        throw new NullPointerException("Can't push a null element");
    }

    addElement(e);
    System.out.println("The element pushed is " + e);
}

