title: java.lang.NullPointerException while using ServletContext
body: <p>I was examining the use of <code>ServletContext</code> when i got the null pointer exception. I don't understand why do i get this exception. </p>
  
  <p>I have set the attribute in the <code>context</code> object from one class and then try to retrieve that from the second class using <code>getAttribute(...)</code>.</p>
  
  <pre><code>package ServletContext; // servlet1
  
  import javax.servlet.*; 
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  
  public class servlet1 extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
      LinkedList list = new LinkedList();
      list.add("suhail");
      ServletContext servletContext = getServletContext();
      servletContext.setAttribute("name", list);
    }
  }
  </code></pre>
  
  <hr>
  
  <pre><code>package ServletContext;  // servlet2
  
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  
  public class servlet2 extends HttpServlet {
   public void doGet(HttpServletRequest request , HttpServletResponse response) throws IOException,ServletException {
      LinkedList list2 = new LinkedList();
      ServletContext context = getServletContext();
      list2 = (LinkedList)context.getAttribute("name");
      PrintWriter writer = response.getWriter();
      response.setContentType("text/plain");
      writer.println(list2.pop()); //**15th statement**
    }
  }
  </code></pre>
  
  <p>Exception is :</p>
  
  <pre><code>HTTP Status 500 -
  
  type Exception report
  
  message
  
  description The server encountered an internal error () that prevented it from fulfilling this request.
  
  exception
  
  java.lang.NullPointerException
  ServletContext.servlet2.doGet(servlet2.java:15)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
  org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
  </code></pre>
  
  <p>note The full stack trace of the root cause is available in the Apache Tomcat/7.0.11 logs.</p>
  
  <p>Why am i getting this exception ? <code>list</code> should be initialized in servlet2</p>