A static block is a special block of code in Java that is executed only once when the class is loaded into memory by the JVM. It is primarily used to initialize static variables or perform one-time setup operations before any object is created or any static method is called.
Key Points: • A static block executes only once during class loading. • It is used for initializing static variables with complex logic. • Multiple static blocks can exist in a class and are executed in the order they appear. • Static blocks execute before constructors and before the main() method. • They are commonly used for configuration loading and one-time initialization tasks.
Example: Suppose an application needs to initialize a static database URL before any object is created. A static block can perform this initialization.
Code Example:
class Demo {
static String message;
static {
message = "Static Block Executed";
System.out.println(message);
}
public static void main(String[] args) {
System.out.println("Main Method Executed");
}
}Output:
Static Block Executed Main Method Executed
Execution Order Example:
class Demo {
static {
System.out.println("Static Block");
}
Demo() {
System.out.println("Constructor");
}
public static void main(String[] args) {
System.out.println("Main Method");
new Demo();
}
}Output:
Static Block Main Method Constructor
Multiple Static Blocks:
class Demo {
static {
System.out.println("Static Block 1");
}
static {
System.out.println("Static Block 2");
}
public static void main(String[] args) {
}
}Output:
Static Block 1
Static Block 2Common Use Cases:
• Initializing static variables • Loading configuration files • Registering database drivers • Performing one-time application setup • Initializing shared resources
Important Notes:
• Static blocks cannot accept parameters. • They cannot return any value. • They execute only once per class loading. • If an unhandled exception occurs inside a static block, class initialization fails with ExceptionInInitializerError.
Interview Tip: A concise interview answer is:
"A static block is a special initialization block that executes once when a class is loaded into memory. It is mainly used to initialize static variables and perform one-time setup tasks before any object creation or method execution."