Initializer
Initializer
In Java, if you see code enclosed within curly braces { } outside of any method,
it’s likely an initializer block. Initializer blocks are sections of code that are
executed when an instance of the class is created, or when the class itself is
loaded, depending on the type:
public MyClass() {
System.out.println("Constructor");
}
}
Here, if you create a new instance of MyClass, the initializer block will print
"Instance initializer block" before "Constructor".
If the block is marked with the static keyword, it becomes a static initializer
block, which runs only once when the class is first loaded.
This is useful for class-level setup, like initializing static variables.
Syntax:
This block runs only once, the first time MyClass is loaded.