Question: Where do static methods and static variables get stored in memory?
Answer: Static variables and static methods are called class members. Static variables are common
to all objects of that class. So instead of objects they are associated with the class and it is
located in a fixed location memory. Hence any change made to the static variable is visible to all
the objects. Both static variables and static methods are stored inside heap memory, but there is
a special area of the heap called "Permanent Generation" (or PermGen).
Only the variables and their primitives or references are stored in Permanent Generation space.
If a static variable is holding a reference to an object, then the reference would be stored in
PermGen and the object would be stored in the normal heap space. The below example makes it more clear:
Since variable 'a' is a static int, its value 10 is stored in "Permanent Generation" space.
static int a= 10;
Since variable 'obj' is a static object, it is stored in "Permanent Generation" space.
But, the object would be stored in heap memory.
But, the object would be stored in heap memory.
static MyObject obj = new MyObject();
No comments:
Post a Comment