Open In App

What is Class Loading and Static Blocks in Java?

Last Updated : 13 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

  1. Static Block
  2. Static Variable
  3. Static Method

Static-Block-in-Java

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.

  1. Compilation of java file.
  2. Execution of java file.
  3. Java virtual machine JVM is calling main method in the program.
  4. Class is loaded and all the necessary information is stored in memory by now.
  5. Execution of static block begins.

Execution-of-
Static-Block

Example      

Java




// Java Program to illustrate static block concept
// alongside discussing the class loading
  
// Importing all input output classes
import java.io.*;
  
// Class
class GFG {
  
    // Static block
    static
    {
        // Static block will be executed first
        // before anything else
  
        // Print message
        System.out.println(
            "I am static block and will be shown to eyeballs first no matter what");
    }
  
    // Main driver method
    public static void main(String[] args)
    {
        // Print message
        // Now main method will execute
        System.out.println(
            "I am the only line in main method but static block is hindering me to display first");
    }
}


Output

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads