It is used to initialize the static data member, It is excuted before main method at the time of classloading.
In Java, a static block is a block of code that is executed only once when the class is first loaded into memory. It is used for initializing static variables or performing any setup that is required before any static methods or variables are accessed.
Initialization: Static blocks are often used to initialize static variables or perform setup tasks that need to be done only once.
Execution: A static block is executed when the class is loaded by the Java Virtual Machine (JVM), before any instances of the class are created or any static methods or variables are accessed.
Order of Execution: If a class has multiple static blocks, they are executed in the order in which they appear in the code.
No Instance Context: Static blocks do not have access to instance variables or methods. They can only access static variables and methods of the class.
public class MyClass { static { // Static initialization code } }
public class MyClass { static int count; // Static block to initialize static variables static { count = 0; System.out.println("Static block executed"); } public MyClass() { count++; System.out.println("Constructor executed"); } public static void main(String[] args) { MyClass obj1 = new MyClass(); // Static block is executed first MyClass obj2 = new MyClass(); // Constructor is executed each time an object is created System.out.println("Count: " + MyClass.count); } }
MyClass is loaded, the static block executes first, initializing the count variable and printing "Static block executed".MyClass object is created, the constructor runs and increments the count, printing "Constructor executed".count variable is a static variable shared among all instances of the class and is initialized in the static block.Static blocks are a useful feature for initializing class-level resources that need to be set up once and shared across all instances of the class.
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.