Eager Initialization over static block

374 Views Asked by At

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?

4

There are 4 best solutions below

2
On BEST ANSWER

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.

0
On

Static block is used when you are doing the logical operation or processing when class is getting loaded into memory then variables getting intialized

Example:

public class R {

  public static int example;

  static {
    int example1 = 2 + 3;
    example = example1;
  }


  public static void main(String[] args) {
    System.out.println(example);   // print 5
  }

}

In case if the value is already known then can be directly assigned (Case 2);

1
On

One reason you might use a static block is if you want to set more than one variable:

private static int n;
private static String s;
static {
    if (someExpensiveOperation()) {
        n = 123;
        s = "foo";
    } else {
        n = 456;
        s = "bar";
    }
}
0
On

I think that if you need to initialize a static variable with a starting value available, you can use Case 2, while if you need to initialize a variable according to some logical operations, you can put it in a block of static code and execute his initialization through it