As the title says, what exactly is the difference between
public static String myString = \"Hello World!\";
and
public stat
Difference between static initializer block and regular static initialization.
In case of variable initialization both are same.
But If we want to connect with database only once or any operation you want to load once. Then write the code in static block because its execute only once when first class load no matter how many objects of that type you create.
EDIT :
You can also construct a similar block:
{
// Do Something...
}
Example:
public class Demo {
static{
System.out.println("Static");
}
{
System.out.println("Non-static block");
}
public static void main(String[] args) {
Demo demo = new Demo();
Demo demo2 = new Demo();
}
}
Output:
Static
Non-static block
Non-static block