What is static block?
Answer:
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.
Characteristics of Static Blocks
-
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.
Syntax
public class MyClass { static { // Static initialization code } }
Example
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); } }
h3>
Explanation
- Static Block Execution: When the
MyClass
is loaded, the static block executes first, initializing thecount
variable and printing "Static block executed". - Constructor Execution: Each time a
MyClass
object is created, the constructor runs and increments thecount
, printing "Constructor executed". - Static Variable Access: The
count
variable is a static variable shared among all instances of the class and is initialized in the static block.
Use Cases
- Initialization: Setting up static resources or configurations.
- Logging: Performing logging or diagnostics when the class is loaded.
- Configuration: Loading configuration files or settings that are needed for the class.
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.
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.