Search code examples
javavariablesinitializationdeclaration

What is the difference between initializing a static variable when it is declared vs initializing it in a static block?


I have found this use in the link below, in step 5, in a guide for Service Locator design pattern https://www.tutorialspoint.com/design_pattern/service_locator_pattern.htm

I don't understand why they used this structure.

public class ServiceLocator {
   private static Cache cache;

   static {
      cache = new Cache();      
   }
}

vs

   private static Cache cache = new Cache();

Solution

  • In this particular instance the result is exactly the same. You can use static blocks if you need to apply more logic than just simple field initialization.

    If you aim to improve code readability you should just initialize a static variable:

    private static Cache cache = new Cache();