Home page

Friday, June 16, 2023

Static Block in JAVA

A static block in Java is a block of code that is executed only once when the class is loaded into memory. It is used to initialize static members of the class or perform any other one-time initialization tasks.

The purpose of using a static block is to ensure that certain code is executed before the class is used, such as initializing static variables, loading resources, or performing any necessary setup operations.

Here's an example of how you can use a static block in Java:

public class StaticBlockExample {

    static {

        // Code inside the static block

        System.out.println("This is a static block.");

        // Perform initialization tasks, load resources, etc.

    }

    public static void main(String[] args) {

        // Code inside the main method

        System.out.println("This is the main method.");

    }

}

In this example, we have a class called StaticBlockExample. Inside the class, we define a static block using the static keyword followed by curly braces {}.

The code inside the static block is executed only once, before the class is used. In this example, we simply print a message to the console.

When we run the program, the static block is executed first, followed by the main method. The output will be:
This is a static block.
This is the main method.

It's important to note that static blocks cannot be called explicitly like methods. They are automatically executed when the class is loaded into memory.

No comments:

Post a Comment