Understanding Java Static Blocks and Their Role in Initialization

preview_player
Показать описание
Static initializers, also known as "static blocks", are used in Java to initialize static variables or to perform actions when a class is loaded. They are executed only once, when the class is loaded by the Java Virtual Machine (JVM). To create a static initializer, simply use the static keyword followed by a pair of braces {} and write the initialization code within those braces.

In this example, we have a static variable staticCounter and a static initializer block that sets the value of this variable to 5. The code inside the static block will be executed only once when the class is loaded.
Рекомендации по теме