what are static blocks and static initializer in java with example

What are static blocks and static initializer in java with example?

In Java, static blocks and static initializers are used to initialize static variables and perform one-time initialization tasks for a class. They are executed when the class is loaded into memory, and they are executed only once, regardless of how many instances of the class are created. Static blocks and static initializers are often used to perform tasks such as loading native libraries, initializing static variables, or setting up static data structures.

Static Blocks:

Static blocks are used to initialize static variables of a class. They are executed when the class is loaded into the memory, and they are defined using the static keyword followed by a block of code inside curly braces. Static blocks are executed in the order they appear in the class.

Here’s an example of a static block:

Java
/*
 * Author: Zameer Ali
 * */

public class MyClass {
    static {
        // Code inside this static block will be executed when 
        // the class is loaded
        System.out.println("Static block is executed.");
    }

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

In this example, the static block will be executed when the class MyClass is loaded into the memory.

Static Initializers:

Static initializers are similar to static blocks, but they allow you to catch exceptions during initialization. They are defined using the static keyword followed by a block of code inside curly braces, just like static blocks. However, static initializers can throw checked exceptions, unlike static blocks.

Here’s an example of a static initializer:

Java
/*
 * Author: Zameer Ali
 * */

public class MyClass {
    static {
        try {
            // Code inside this static initializer can throw exceptions
            // Perform initialization tasks here
            System.loadLibrary("myLibrary");
        } catch (UnsatisfiedLinkError e) {
            System.err.println("Error loading native library: " + e.getMessage());
        }
    }

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

In this example, the static initializer tries to load a native library using System.loadLibrary("myLibrary"). If the library loading fails, it catches the UnsatisfiedLinkError and prints an error message.

Both static blocks and static initializers are executed when the class is loaded, and they provide a way to perform static initialization tasks in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *