What are static blocks and static initializer in java with example?
In Java, static blocks and static initializers are used to initialize static variables and perform one-time initialization tasks for a class. They are executed when the class is loaded into memory, and they are executed only once, regardless of how many instances of the class are created. Static blocks and static initializers are often used to perform tasks such as loading native libraries, initializing static variables, or setting up static data structures.
Static blocks are used to initialize static variables of a class. They are executed when the class is loaded into the memory, and they are defined using the
static keyword followed by a block of code inside curly braces. Static blocks are executed in the order they appear in the class.
Here’s an example of a static block:
In this example, the static block will be executed when the class
MyClass is loaded into the memory.
Static initializers are similar to static blocks, but they allow you to catch exceptions during initialization. They are defined using the
static keyword followed by a block of code inside curly braces, just like static blocks. However, static initializers can throw checked exceptions, unlike static blocks.
Here’s an example of a static initializer:
In this example, the static initializer tries to load a native library using
System.loadLibrary("myLibrary"). If the library loading fails, it catches the
UnsatisfiedLinkError and prints an error message.
Both static blocks and static initializers are executed when the class is loaded, and they provide a way to perform static initialization tasks in Java.