why can't we initializa the fields in a constructor in the servlet?

What exactly are you trying to do, and what error messages / unwanted effects are you getting / seeing?

The code in question would help, alot.

never assume a servlet's constructor will be called.
In fact unless it's a no-args constructor it's guaranteed to not be called!

Typically a servlet is instantiated once, when it is first needed, per member of a cluster (which means once for most people, as most people don't run their applications in a clustered environment).
After that the servlet engine will keep it in memory and launch a new thread for each time a service method on that servlet is requested to be executed.

i WANT TO INITIALIZE MY FIELDS IN THE CONSTRUCTOR IN A SERVLET

You still haven't provided your code, so we can still only guess. If you are doing things in the "standard" constructor, it should work, but I wouldn't count on it. If you have any other constrcutor, then forget it, as it will never be called. For the most part, however, instance/class variables in a Servlet are usually not a good thing. Most people just starting use them wrongly and have from very serious side effects from it.

As I said, provide your code.

Satish, store the client information / state in client session i.e. session variables. Since the servlet class is loaded in memory on its first invocation and the client reqests just result in the creation of thread, storing state in servlet instance variables would make them kind of global, i.e. accessible by each and every client.

To store common information related to the entire web application, look into the <context-param> element of deployment descriptor. To store common information related to a particular servlet, look into <init-param> element of deployment descriptor.

he should learn about the object lifecycle in a servlet container before thinking of wanting to do something that's utterly unusual.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.