What is the difference between below two codes?
Class A { private static A obj; static{ obj= new A();} }
and
Class A { private static A obj=new A(); }
What is the difference between below two codes?
Class A { private static A obj; static{ obj= new A();} }
and
Class A { private static A obj=new A(); }
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!!!");
}