title: NullPointerException in push() method of Stack in Java
body: <p>How to I incorporate <code>NullPointerException</code> in the following <code>push()</code> method for a stack in Java?</p>
  
  <pre><code>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);
      }
  </code></pre>
  
  <p>In the PSVM, whenever I call the <code>push()</code> method it gives out the NullPointerException without adding to the stack.</p>
  
  <pre><code>public static void main(String[] args) {
          try {
              SortableStack&lt;Object&gt; s = new SortableStack&lt;Object&gt;();
              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!");
          }
  }
  </code></pre>