When Are Static And Non Static Variables of The Class Initialized

The static variables are initialized when the class is loaded Non static variables

are initialized just before the constructor is called.

In Java, static and non-static variables of a class are initialized at different times:

  1. Static Variables:
    • Static variables, also known as class variables, are initialized when the class is loaded into the memory by the Java Virtual Machine (JVM).
    • They are initialized only once, and their values are shared among all instances of the class.
  2. Non-Static Variables (Instance Variables):
    • Non-static variables, also known as instance variables, are initialized when an object of the class is created using the new keyword.
    • Each object has its own copy of instance variables, and their values can vary from one object to another.

Here’s a simple example to illustrate the initialization of static and non-static variables:

java
public class Example {
// Static variable
static int staticVar = 10;
// Non-static variable
int nonStaticVar;

// Constructor to initialize non-static variables
public Example(int value) {
this.nonStaticVar = value;
}

public static void main(String[] args) {
// Static variable is already initialized
System.out.println(“Static Variable: “ + Example.staticVar);

// Creating an object of the class initializes non-static variables
Example obj1 = new Example(20);
Example obj2 = new Example(30);

// Each object has its own copy of non-static variable
System.out.println(“Object 1 – Non-Static Variable: “ + obj1.nonStaticVar);
System.out.println(“Object 2 – Non-Static Variable: “ + obj2.nonStaticVar);
}
}

In this example, staticVar is initialized when the class is loaded, and nonStaticVar is initialized when each object is created.