Static initialization block

Asked 2 years ago, Updated 2 years ago, 118 views

Until now, I understood that "static initialization block" is used when it is impossible to set the value of the static field with one line.

But I don't know why I need a special block for that work. For example, you defined the field as static (without assigning a value). Then write a line of code that generates and assigns a value to the static field above.

Why are those codes static {...Is it supposed to be in a special block like }?

java static initialization static-block

2022-09-22 13:28

1 Answers

non - static block.:

{
    // // Do Something...
}

This block will be called every time an instance of the class is created. static block will be called once when the class itself initializes, regardless of how many objects of that class type are created.

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();
    }
}

It's printed as follows:

Static
Non-static block
Non-static block


2022-09-22 13:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.