In the below program:
class Main
{
static string staticVariable = "Static Variable";
string instanceVariable = "Instance Variable";
public Main(){}
}
The instanceVariable
will be stored inside the memory allocated for object instance. Where will the staticVariable
be stored, is it stored in the object instance itself or somewhere else? If its stored somewhere else, how are the memory locations connected?
After the java 8 version, static variables are stored in the heap memory.
Static Memory Allocation: Static Memory is allocated for declared variables by the compiler. The address can be found using the address of operator and can be assigned to a pointer. The memory is allocated during compile time.
Memory allocation for a static variable happens only once in the class area when the class is loaded in the memory. It is also known as a class variable. It is common to all the objects of the class. In this, a single copy of a static variable is created and shared among all the objects of the class.
Static variables are stored in RAM, just like your global variables.
Memory for static variables are normally held in some rooted (and hidden) object[]
. This can be seen doing a !gcroot on the object in WinDbg (with SOS).
Just to add, these references can never be GC'ed (unless you null the field), as I discovered recently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With