java – What is a static block for?

Question:

Where in real life can such a block be used in programming? Why then a constructor? Yes, I understand that the constructor will be called every time an instance of the class is created, and the static block will be called once. But at what point will the initialization of the block statics take place and where is it actually used?

Answer:

Static blocks are called at the time of class initialization (when the ClassLoader will load it into MetaSpace, more details in the JLS ), and can be used to initialize static variables. Why call the initialization of static variables in the constructor every time, if you can do it once, thus not wasting resources on reinitializations?

Scroll to Top