Static block vs initialization block in Java?

Possible duplicate:
Static Initialization Blocks

Consider the following code:

public class Test { { System.out.println("Empty block"); } static { System.out.println("Static block"); } public static void main(String[] args) { Test t = new Test(); } } 

We understand that a static block will be executed first, followed by an empty block. But the problem is that I could never understand the real usefulness of an empty block. Can anyone show a real example in which -

  • Both static and empty blocks are used.
  • Both static and empty blocks have different utilities.
+64
java initialization-block static-block
Sep 23
source share
2 answers

They are designed for two completely different purposes:

  • A static initializer block will be called when the class loads and will not have access to instance variables or methods. According to a comment by @Prahalad Deshpande, it is often used to create static variables.
  • A non-static initializer block, on the other hand, is created only when the object is built, will have access to instance variables and methods, and (according to the important amendment proposed by @EJP), it will be called at the beginning of the constructor, after the super constructor has been called (explicitly or implicitly) and before calling any other subsequent constructor code. I saw how it was used when a class has several constructors and needs the same initialization code, which is required for all constructors. As with constructors, you should avoid calling non-finite methods in this block.

Please note that there are many answers to this question in stackoverflow, and it would be useful for you to search and view similar questions and their answers. For example: static-initialization-blocks

+89
Sep 23
source share

A static block is executed whenever your class is loaded. An empty block is executed whenever you instantiate a class. Try comparing them:

one.

 public static void main(String[] args) { Test t = new Test(); } 

2.

 public static void main(String[] args) { } 



Outputs:

one.

Static block
Empty block

2.

Static block

In Layman's words, a static block gets only once , regardless of how many objects of this type you create.

+20
Sep 23
source share



All Articles