A static block in Java is a block of code that is executed only once when the class is loaded into memory. It is used to initialize static members of the class or perform any other one-time initialization tasks.
The purpose of using a static block is to ensure that certain code is executed before the class is used, such as initializing static variables, loading resources, or performing any necessary setup operations.
Here's an example of how you can use a static block in Java:
public class StaticBlockExample {
static {
// Code inside the static block
System.out.println("This is a static block.");
// Perform initialization tasks, load resources, etc.
}
public static void main(String[] args) {
// Code inside the main method
System.out.println("This is the main method.");
}
}
No comments:
Post a Comment