Static Block VS. Initializer Block in Java

Static block vs. initializer block in Java?

They're for two very different purposes:

  • The static initializer block will be called on loading of the class, and will have no access to instance variables or methods. As per @Prahalad Deshpande's comment, it is often used to create static variables.
  • The non-static initializer block on the other hand is created on object construction only, will have access to instance variables and methods, and (as per the important correction suggested by @EJP) will be called at the beginning of the constructor, after the super constructor has been called (either explicitly or implicitly) and before any other subsequent constructor code is called. I've seen it used when a class has multiple constructors and needs the same initialization code called for all constructors. Just as with constructors, you should avoid calling non-final methods in this block.

Note that this question has been answered many times in stackoverflow and you would do well to search and review the similar questions and their answers. For example: static-initialization-blocks

static block vs initializer block vs constructor in inheritance

A static block is called once, when the class is loaded and initialized by the JVM. An instance initializer is executed when an instance of the class is constructed, just like a constructor.

Static and Instance initializers are described in the Java Language Specification

Static Initialization Blocks

The non-static block:

{
// Do Something...
}

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

Example:

public class Test {

static{
System.out.println("Static");
}

{
System.out.println("Non-static block");
}

public static void main(String[] args) {
Test t = new Test();
Test t2 = new Test();
}
}

This prints:

Static
Non-static block
Non-static block

Difference between the static initializer block and regular static initialization

For your example, there is no difference. But as you can see,

public static String myString = "Hello World!";

can only accept an expression to initialize the variable. However, in a static initializer (JLS 8.7), any number of statements may be executed. E.g. it's possible to do this:

static
{
myString = "Hello";
myString += " ";
myString += "World";
}

For your example, there's obviously no need to do that, but it's possible for the initialization of a variable to take more than an expression, perhaps many statements, so Java made static initializers.

Static and Non-Static initialization blocks in Java

Non-static initialization blocks will be called on instance creation.

You never create a new instance, so the block is not executed.

what is the difference between Initializing a static object inside static block and outside?

In your examples mentioned above both the program is doing the same thing. So you can't judge what is difference between initializing static object and static block. Static block will be called only once at the time of loading the class by the JVM. Purpose of static block is to initialize the static variables and calling static methods. Remember one thing,initialize before you use any resources and for that this is one option which wil be called even before calling the constructor of the class. If you have the requirement to initialize the static variables at the time of loading the class or calling the methods at the time of loading the class to initialize something then in that case static block will be helpful. Here is the example of creating the static object and initializing it in static block.

private static List<String> arrList = new ArrayList<>();
static{
arrList.add("Hello");
arrList.add("World!!!");
}

static initialization block vs constructor java

Strictly speaking, static initializers are executed, when the class is initialized.

Class loading is a separate step, that happens slightly earlier. Usually a class is loaded and then immediately initialized, so the timing doesn't really matter most of the time. But it is possible to load a class without initializing it (for example by using the three-argument Class.forName() variant).

No matter which way you approach it: a class will always be fully initialized at the time you create an instance of it, so the static block will already have been run at that time.

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

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

Static Initializers vs Instance Initializers vs Constructors

The main difference between them is the order they are executed. To illustrate, I will explain them with an example:

public class SomeTest {

static int staticVariable;
int instanceVariable;

// Static initialization block:
static {
System.out.println("Static initialization.");
staticVariable = 5;
}

// Instance initialization block:
{
System.out.println("Instance initialization.");
instanceVariable = 10;
}

// Constructor
public SomeTest() {
System.out.println("Constructor executed.");
}

public static void main(String[] args) {
new SomeTest();
new SomeTest();
}
}

The output will be:

Static initalization.
Instance initialization.
Constructor executed.
Instance initialization.
Constructor executed.

Briefly talking:

  • Static initialization blocks run once the class is loaded by the JVM.
  • Instance initialization blocks run before the constructor each time you instantiate an object.
  • Constructor (obviously) run each time you instantiate an object.


Related Topics



Leave a reply



Submit