0

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?

  • 1
    It's indeed rarely needed. But it can be handy when you just want to trigger a side effect (like loading a class or a native library), or when you want to initialize several variables using more than an expression. – JB Nizet Nov 23 '18 at 16:49
  • 1
    Static blocks can also initialize a more complex class, like a map or a list, than can be done with a single line. For simple static fields like Strings or primitives obviously a static block is not needed. – markspace Nov 23 '18 at 16:54

4 Answers4

2

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

Federico
  • 415
  • 1
  • 3
  • 15
1

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.

markspace
  • 10,621
  • 3
  • 25
  • 39
  • 1
    You can actually: `private final static Map stooges = createStooges();` – JB Nizet Nov 23 '18 at 17:19
  • Also, in Java 11: `private static final var stooges = Map.of("Larry", "Larry Fine", "Moe", "Moe Howard", "Curly", "Curley Howard");`. Or, if you want a mutable one, `... = new HashMap<>(Map.of(...))`. – Klitos Kyriacou Nov 23 '18 at 17:42
1

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";
    }
}
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
  • I'll take that as, if the initialization of variable(s) is more complicated than done in one line as @markspace mentioned. Like for example, conditionally, as in your example. Thanks. – ConfusedCoder Nov 27 '18 at 17:50
0

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);