Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the static initializer block and regular static initialization

As the title says, what exactly is the difference between

public static String myString = "Hello World!";

and

public static String myString;

static {
    myString = "Hello World";
}

is there any important difference other than the structure ?

like image 218
Cemre Mengü Avatar asked Mar 18 '13 19:03

Cemre Mengü


People also ask

What are the differences between static initializers and instance initializers?

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.

What is the difference between static block and static method?

Static methods belong to the class and they will be loaded into the memory along with the class, you can invoke them without creating an object. (using the class name as reference). Whereas a static block is a block of code with a static keyword. In general, these are used to initialize the static members.

What is the difference between static block and instance initializer block?

Static blocks can be used to initialize static variables or to call a static method. However, an instance block is executed every time an instance of the class is created, and it can be used to initialize the instance data members.

What is static and initializer block and what is need of both?

A static initialization block loads as soon as a class loads and it is not associated with a call to the constructor of a class for object creation. An instance initialization block is only executed when there is a call to the constructor for creating an object.


1 Answers

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.

like image 166
rgettman Avatar answered Oct 27 '22 01:10

rgettman