When Are The Static Variables Loaded into The Memory

: During the class load time.

In Java, static variables are loaded into memory when the class that contains them is loaded by the Java Virtual Machine (JVM). The class loading process occurs when the class is first referenced in the program, either by creating an instance of the class, accessing a static member, or invoking a static method. The static variables are initialized at this point.

It’s important to note that the initialization of static variables happens only once, and it occurs before any instances of the class are created. The static variables retain their values throughout the lifetime of the program.

Here’s a simple example to illustrate this:

java
public class Example {
// Static variable
static int staticVariable = 10;
public static void main(String[] args) {
// The class is loaded when main method is called
// Static variable is loaded and initialized
System.out.println(“Static variable value: “ + staticVariable);// Create an instance of the class
Example example = new Example();

// Access static variable through the instance (not recommended)
// It still refers to the same static variable
System.out.println(“Static variable value through instance: “ + example.staticVariable);
}
}

In this example, the static variable staticVariable is loaded into memory when the class is first referenced (in this case, when the main method is called).