Are static variables re-initialized and stored multiple times in memory when instance of a class is created?
Are static variables re-initialized and stored multiple times in memory when instance of a class is created?
No, static variables are not re-initialized or stored multiple times in memory when instances of a class are created. Here is how static variables work in Java:
Characteristics of Static Variables:
- Single Instance per Class: A static variable is associated with the class itself, rather than with any specific instance of the class. This means that no matter how many instances of the class you create, there will always be only one copy of the static variable.
- Memory Allocation: Static variables are allocated memory only once, when the class is loaded into memory by the Java Virtual Machine (JVM). This allocation happens in the method area (part of the JVM's memory), which is separate from the memory areas used for instance variables (which are stored in the heap).
- Initialization: Static variables are initialized once, at the start of the program execution, when the class is first loaded. This happens before any instances of the class are created.
- Shared Across Instances: All instances of the class share the same static variable. Any changes made to the static variable through one instance are visible to all other instances of the class.
Example:
public class Example {
static int staticVariable = 0;
int instanceVariable = 0;
public Example() {
staticVariable++;
instanceVariable++;
}
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
System.out.println("Static Variable: " + Example.staticVariable);
// Output: Static Variable: 2
System.out.println("Instance Variable of obj1: " + obj1.instanceVariable);
// Output: Instance Variable of obj1: 1
System.out.println("Instance Variable of obj2: " + obj2.instanceVariable);
// Output: Instance Variable of obj2: 1
}
}
Summary:
- Single Instance: There is only one copy of a static variable per class.
- Initialization: Static variables are initialized once when the class is loaded.
- Shared State: All instances of the class share the same static variable.
- Memory Efficiency: Static variables are stored in a fixed memory area, reducing the overhead of storing multiple copies.
Therefore, static variables are not re-initialized and stored multiple times in memory when instances of a class are created. They remain consistent across all instances of the class.
Comments
Post a Comment