0

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();    }
Vipin CP
  • 3,642
  • 3
  • 33
  • 55
  • 3
    There is no difference. I would use second one when i have to eagerly create an object like you did. While static block if i have to define the object body say add objects in list. – SMA Jun 03 '16 at 06:09
  • Then why people are using the first one , even they don't have any logic to write inside static block. I have seen that code many times and bit confused. Thanks @SMA – Vipin CP Jun 03 '16 at 06:14
  • 1
    Consider creating a _constant_ map with some entries: `private static final Map MY_MAP = new HashMap<>();`. How to put the values in such an initialization? Use a static initializer: `static { MY_MAP.put(...); MY_MAP.put(...); }` – Seelenvirtuose Jun 03 '16 at 06:17
  • 1
    @vipincp Why? Because when there are two ways of doing something, some people will do it one way, and others will do it the other way. It *is* their choice, after all. – Andreas Jun 03 '16 at 06:29
  • There are plenty of information on the net, and already here: http://stackoverflow.com/questions/2420389/static-initialization-blocks – Manuel Vera Silvestre Jun 05 '16 at 08:10

1 Answers1

0

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!!!");
}
RCS
  • 1,370
  • 11
  • 27