static blocks and static initializers
In Java, static blocks are blocks of code within a class that are executed when the class is first loaded into memory by the JVM. They are primarily used for initializing static variables or for executing setup code that should run once.

Table of Contents
class Example {
static {
// Initialization code
System.out.println("Static block executed.");
}
}
class AppConfig {
static String appName;
static int maxUsers;
static {
appName = "MyApplication";
maxUsers = 100;
System.out.println("Static block executed: AppConfig initialized.");
}
}
public class MainApp {
public static void main(String[] args) {
// The static block in AppConfig class will be executed when the class is first accessed
System.out.println("Application Name: " + AppConfig.appName);
System.out.println("Maximum Users: " + AppConfig.maxUsers);
}
}
Key Points
- Initialization: Static blocks are used to initialize static variables or execute code that should run once when the class is loaded.
- Execution Order: Static blocks are executed in the order they appear in the class.
- Multiple Static Blocks: A class can have more than one static block, and they will be executed sequentially in the order they are defined.
Example
Consider an example where we need to initialize settings for a messaging system.
class MessagingConfig {
static String defaultServer;
static int defaultPort;
static {
defaultServer = "smtp.example.com";
defaultPort = 587;
System.out.println("Static block executed: MessagingConfig initialized with server " + defaultServer + " and port " + defaultPort);
}
}
public class MessagingApp {
public static void main(String[] args) {
// The static block in MessagingConfig class will be executed when the class is first accessed
System.out.println("Default Server: " + MessagingConfig.defaultServer);
System.out.println("Default Port: " + MessagingConfig.defaultPort);
}
}
In this example, the MessagingConfig class has a static block that initializes the default server and port for a messaging system. When the MessagingConfig class is first accessed, the static block is executed, setting up these default configurations.
Summary
Static blocks and static initializers in Java are powerful tools for performing one-time setup tasks and initializing static variables when a class is loaded. The provided examples illustrate how static blocks can be effectively used to set up configurations in different scenarios, ensuring that the content is unique and tailored specifically for your needs.