Java can initialize the static variable int a = 1 directly or int a first and then a = 1 in the static code block. What exactly is the function of the static code block?

what scenario requires a static code block, or a normal code block? now that you can initialize yourself, in what context do code blocks and static code blocks use

Mar.24,2021

non-static code blocks are not used much, but static code blocks are more commonly used, such as loading a configuration file when the class is initialized.


first of all, both code blocks and static code blocks are blocks, and both can initialize a piece of code. The advantage over direct initialization is that it is easier to maintain because they are all put together.
secondly, the difference between code blocks and static code blocks is that static code blocks are executed only once when such objects are created for the first time or when static resources are called for the first time. The code block is executed each time it is created.
also note that static code blocks are generally used to initialize static variables, while code blocks are used to initialize ordinary variables.

Menu