Class Loading is the process of storing the class-specific information in the memory. Class-specific information means, information about the class members, i.e., variables and methods. It is just like that before firing a bullet, first, we need to load the bullet into the pistol. Similarly, to use a class first we need to load it by a class loader. Static block runs only once in the life of a class. It can only access the static members and will only belong to the class.
Static Block is just like any block of code beginning with a ‘static’ keyword is a static block. Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME”.
Execution Order: For every static block, there is an order in which static block/method/variable gets initialized.
- Static Block
- Static Variable
- Static Method
Now figuring out the connection between class loading and static block after having an idea over the static block and class loading, it is found that execution of a static block happens when a class gets loaded for the first time. It is a series of steps.
Illustration: Showcasing generic execution of that static block is supposed to happen with series of steps as mentioned.
Randomly considering a java file ‘File.java’, having a static block in it is followed by a series of steps as mentioned.
- Compilation of java file.
- Execution of java file.
- Java virtual machine JVM is calling main method in the program.
- Class is loaded and all the necessary information is stored in memory by now.
- Execution of static block begins.
I am static block and will be shown to eyeballs first no matter what I am the only line in main method but static block is hindering me to display first
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.