Java : in what order are static final fields initialized?

sangfroid picture sangfroid · Dec 15, 2010 · Viewed 15.6k times · Source

Okay, so say I have a class that looks like this :

public class SignupServlet extends HttpServlet {
    private static final Logger SERVLET_LOGGER=COMPANYLog.open(SignupServlet.class);
    private static final ExceptionMessageHandler handler = new ExceptionMessageHandler();   
    private static final SignupServletObservableAgent signupObservableAgent = 
        new SignupServletObservableAgent(null, SERVLET_LOGGER);
}

Can I count on the class loader to initialize those fields in order, such that I can rely on SERVLET_LOGGER to be instantiated before signupObservableAgent?

Answer

Laurence Gonsalves picture Laurence Gonsalves · Dec 15, 2010

Yes, they are initialized in the order in which they appear in the source. You can read all of the gory details in The Java Language Specification, ยง12.4.2. See step 9, which reads:

... execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block, except that final class variables and fields of interfaces whose values are compile-time constants are initialized first ...