Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use static initialization block in java? [duplicate]

Tags:

java

static

Why should I use static initialization block when I can initialize static members through a constructor?

like image 596
Bhushan Avatar asked Mar 06 '13 11:03

Bhushan


2 Answers

Firstly, you might never have any instances of your class. Or you might want to have the static members iniailized before you have any instances of the class.

Secondly, initializing static members from constructors is more work:

  • you'll need to make sure that every constructor does this;
  • you need to maintain a flag to keep track of whether static members have been initialized;
  • you have to think about synchronization to prevent race conditions;
  • you may have to consider performance implications of the synchronization, especially if you have many threads creating many instances of your class.

Lastly, it's usually the wrong thing to do conceptually (I say "usually" because there are legitimate uses for lazy initialization).

like image 179
NPE Avatar answered Oct 17 '22 12:10

NPE


A static member is not associated to any instance of the class, while the constructor creates an instance. You may use static members without having a single instance of the class, they will still have to be initialized. In this case a constructor can not do the job.

like image 36
Ivaylo Strandjev Avatar answered Oct 17 '22 14:10

Ivaylo Strandjev