In order to initialize a servlet the initialization code is placed in
-
service() method
-
init() method
-
constructor for HttpServlet()
-
None of the Above
The init() method is the designated place for servlet initialization code in the Servlet API lifecycle. It's called once when the servlet is first loaded. The service() method handles each request. The constructor is not the standard initialization point for servlets - init() guarantees the ServletConfig is available.
The correct place for servlet initialization code is the init() method — correct answer. The Servlet container calls init() exactly once, right after the servlet is instantiated and before it services any requests, making it the designated hook for one-time setup (opening resources, loading config, etc.). service() (and its HTTP-specific counterparts doGet/doPost) is called once per request, so it's the wrong place for one-time init and would repeat the work needlessly. The constructor for HttpServlet is not overridden by user servlets for initialization because the container needs the servlet's ServletConfig, which isn't available until init(ServletConfig) is called — code needing that config can't safely run in a constructor. 'None of the above' is wrong since init() is a valid, standard option.