java

Java Static Block


What is Static Block?

  • The static block is executed only once when the .class file is loaded by the Java Virtual Machine (JVM). 
  • It runs before the execution of any static methods or the creation of any static variables within the class.

Syntax

class MyClass {
    // Static block
    static {
        // Code to initialize static variables or perform other operations

    }

}

Example

public class Main {
    // static block
    static {
        System.out.println("This is a static block!");
    }

	// main method the execution point
    public static void main(String[] args) {
        System.out.println("Main method executed!");
    }
}

Output:

This is a static block!
Main method executed!

Note: In Java, when a class is loaded into the Java Virtual Machine (JVM), the static block is executed before any other code in the class that's why in output “This is a static block!”  came first.

 

Why static block?

 

  • Initializing Static Variables: 

1.  Static blocks are often used to initialize static variables with specific values. 

2. This is useful when you want to set up certain constants or configurations that are shared among all instances of the class.

class MyClass {
    // Static variable
    static int myStaticVariable;

    // Static block to initialize the static variable
    static {
        myStaticVariable = 42;
    }
}

 

  • Loading Drivers or Libraries:

1.  If your class requires the use of external libraries or needs to load a driver, static blocks can be used to handle such tasks.

2. This ensures that the necessary components are set up before any methods are invoked.

public class DatabaseConnector {
    static {
        // Load the database driver or initialize necessary resources
        // ...
    }
}

 

  • Complex Initialization: 

If the initialization of a static variable involves complex logic or needs to handle exceptions, using a static block allows you to encapsulate that logic in a structured manner.

class ComplexInitialization {
    static {
        try {
            // Complex initialization logic
            // ...
        } catch (Exception e) {
            // Handle exceptions during initialization
            // ...
        }
    }
}