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.
Suppose an application needs to initialize a static database URL before any object is created. A static block can perform this initialization.
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");
}
}Static Block Executed
Main Method Executed
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();
}
}Static Block
Main Method
Constructor
class Demo {
static {
System.out.println("Static Block 1");
}
static {
System.out.println("Static Block 2");
}
public static void main(String[] args) {
}
}Static Block 1
Static Block 2A 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.
Last updated: 11 November 2026
Previous question: Is it possible to access non-static members from within a static method?
Next question: Can we print something to the console without a main method in Java?