Search code examples
javastatic-variablesstatic-blockvariable-initialization

Eager Initialization over static block


As I'm trying to understand things better, I'm realizing how less I know. I'm sorry, if this sounds like a simple or silly question.

Do we really need static block, if it is ONLY for initialization of STATIC variables without any other logic coded in the block. We can directly do the eager initialization of those static variables, right?. Because from what I understand, static block gets executed when the class loads, so is the initialization of the static variables. And if it is only for variable initialization, isn't good enough to have the static variable eager-initialized, instead of having a exclusive static block for that.

For example, take the following code, and call it Case 1.

static String defaultName = null;
static String defaultNumber = 0;
static {
defaultName  = "John";
defaultNumber = "+1-911-911-0911";
}     

And the following code, and call it Case 2.

static String defaultName = "John";
static String defaultNumber = "+1-911-911-0911";

So, don't Case 1 and Case 2, give the same result or performance. Is static block necessary at all, in cases like this (for any purpose like readability like having all the data initialization at one place or so) while the Case 2 serves the purpose clean and clear? What am I missing?


Solution

  • Obviously one would never prefer case 1. For case 2, sometimes an initialization is more complicated than can be done in one line.

    public final class Stooges {
    
       private final static Map<String,String> stooges = new HashMap<>();
       static {
          stooges.put( "Larry", "Larry Fine" );
          stooges.put( "Moe", "Moe Howard" );
          stooges.put( "Curly", "Curly Howard" );
       }
    }
    

    Here you can't easily put the initialization of stooges in a single line, so the static block makes it easier (and more readable for a maintainer) to init the values.