Home > Java > javaTutorial > Why Use Static Initialization Blocks in Java?

Why Use Static Initialization Blocks in Java?

Barbara Streisand
Release: 2024-12-20 17:46:14
Original
869 people have browsed it

Why Use Static Initialization Blocks in Java?

Static Initialization Blocks: Why a Separate Block?

You might have encountered the concept of "static initialization blocks" in Java. They are meant to address scenarios where assigning values to static fields cannot be done in a single line. However, you may wonder why a special block is needed for this purpose.

In Java, non-static blocks get executed every time a new instance of the class is created. Static blocks, on the other hand, are executed only once when the class itself is initialized. This holds true regardless of how many objects of that particular class you create.

Consider the following example:

public class Test {

    static {
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = new Test();
    }
}
Copy after login

Output:

Static
Non-static block
Non-static block
Copy after login

In this example, the static block containing "Static" is executed only once when the Test class is initially loaded. The non-static block containing "Non-static block" is executed every time a new instance (t and t2) of the Test class is created.

Therefore, using a static initialization block allows you to perform specific actions or assign values to static fields only once during class initialization, while non-static blocks are used for tasks that need to be performed every time an object of the class is instantiated.

The above is the detailed content of Why Use Static Initialization Blocks in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template