static block in Java | Java Tutorials

This Java tutorials  “static block in java” post is providing clear information about static block including definition, execution flow and reasons to write static block in java application.


 

Static block :

  • Block of statements having no identity.
  • We cannot invoke static block(because no name).
  • JVM invokes the static block automatically.
  • Static block executes at the time of class loading.
  • Static block is optional.
  • Static block executes before main method.

Output screen:

 

 

 

 

 

  • We can define static block anywhere inside the class.
  • Static block executes preceded by main method only.

Output:

 

 

Why static block executes before the main method?

  • Static block provides basic information to start communication.
  • Communication is possible using methods (main method).
  • Without basic information, we cannot communicate.
  • Hence static block executes before main method.

Need of Static block in Java

Can we define more than one static block?

  • Yes allowed.
  • All the static blocks execute in the defined order.
  • main() method executes after all the static blocks execution.

Output:

 

When we use more than one static block in the application?

  • Imagine if class loading information is lengthy.
  • We use modularity programming.
  • We divide complete logic into blocks called modules.

Need of more than One Static block in Java

Share this