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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With