Home >Java >javaTutorial >What is a Static Block in Java and How Does It Work?
Static Block in Java
In Java, one may encounter code blocks enclosed within a static {} syntax, which may be unfamiliar to programmers coming from languages like C . This block of code is known as a static initializer or a "class constructor."
What is a Static Block?
A static block is a code segment that is executed when the class is loaded into memory. Its purpose is to initialize class-wide data or perform any necessary actions before any instance of the class is created.
Unlike instance initializers, which are executed when an object is instantiated, static blocks are executed only once during class loading. They are typically used for tasks such as:
Example:
public class MyClass { static { // Code to initialize class-wide data System.out.println("Static initializer executed"); } public static void main(String[] args) { // Code to create instances and execute instance initializers } }
In this example, the static block will print "Static initializer executed" when the MyClass class is loaded.
Note:
The above is the detailed content of What is a Static Block in Java and How Does It Work?. For more information, please follow other related articles on the PHP Chinese website!