Order of Execution in Java
In Java, the order of execution typically follows these steps:
1. Class Loading: The Java Virtual Machine (JVM) loads the class files into memory. When a class is referenced for the first time, the JVM loads the “.class” file.
2. Static Block Execution: Any static blocks in the class are executed. Static blocks are executed in the order they appear in the class. Static blocks are executed when the class is loaded, and they are executed in the order they appear. If there are multiple static blocks, they are executed sequentially.
3. Static Variable Initialization: Static variables are initialized in the order they are declared. This happens after the static blocks are executed.
4. Main Method Execution: If the class contains a “main” method, the JVM starts execution from this method. Execution starts from the “main” method. This method must be public, static, and return void, and it takes a single argument, an array of “String” (“String[] args”).
Instance Initialization
When an instance of a class is created:
1. Instance Variable Initialization: Instance variables are initialized to their default values.
2. Instance Block Execution: Instance blocks are executed in the order they appear in the class.
3. Constructor Execution: The constructor of the class is executed. If there are multiple constructors, the appropriate one based on the arguments is called.
Example to illustrate the order of execution:
public class ExecutionOrder {
static {
System.out.println("Static block 1");
}
static int staticVar = initializeStaticVar();
static {
System.out.println("Static block 2");
}
int instanceVar = initializeInstanceVar();
{
System.out.println("Instance block 1");
}
{
System.out.println("Instance block 2");
}
public ExecutionOrder() {
System.out.println("Constructor");
}
public static void main(String[] args) {
System.out.println("Main method");
ExecutionOrder eo = new ExecutionOrder();
}
static int initializeStaticVar() {
System.out.println("Static variable initialization");
return 0;
}
int initializeInstanceVar() {
System.out.println("Instance variable initialization");
return 0;
}
}
/* Output:
Static block 1
Static variable initialization
Static block 2
Main method
Instance variable initialization
Instance block 1
Instance block 2
Constructor */
1. Static block 1 and Static variable initialization: Static blocks and static variables are initialized in the order they appear.
2. Static block 2: The next static block is executed.
3. Main method: The JVM starts executing the `main` method.
4. Instance variable initialization: When an instance is created, instance variables are initialized first.
5. Instance block 1 and Instance block 2: Instance blocks are executed in the order they appear.
6. Constructor: Finally, the constructor is executed.