Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is memory allocated for a static variable?

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?

like image 933
gk. Avatar asked Dec 03 '08 13:12

gk.


People also ask

Which memory is used by static variables?

After the java 8 version, static variables are stored in the heap memory.

Does static allocate 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.

Who will allocate the memory for static variables in Java?

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.

Are static variables stored in RAM?

Static variables are stored in RAM, just like your global variables.


1 Answers

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.

like image 122
leppie Avatar answered Oct 16 '22 08:10

leppie