tags:

views:

268

answers:

4

Hi, If we store objects in static fields of an object, how does the JVM allocate the memory for it? Does it live within "implicit"(not sure if I am using the right word) class object? How are static fields different from object fields?

+3  A: 

Static fields are class variables, and are shared amongst all instances of that class. Instance variables (or object fields as I think you are referring to them as) belong to individual instances of a class and are not shared.

As for where they are stored in memory is going to based on the implementation of the JVM and there is no reason two different JVMs would be required to store them in the same place by specification (to the best of my knowledge at least - should insert appropriate spec sheet link here).

NickLarsen
A: 

As NickLarsen said, I don't think there is any JVM specification how exactly static fields are stored. Compile defined constants (static final) will replace most likely the expression during compile time. For variable static fields there will be only two options: The heap or (if existing) the data segment of the JVM.

Thorsten S.
+1  A: 

As Nick's answer says, there is no specific "physical" location stipulated by the language specification, but in terms of a logical mental model that you can reason about, it may help you to think of static fields as being attached to the class object (Foo.class) of the class those fields belong to.

As an aside, the class object is used in other ways (that are stipulated by the language spec) when dealing with static entities: for example, when calling a synchronized static method, the lock is held on the class object of the class that method belongs to.

Chris Jester-Young
A: 

Static fields are part of the class; supposedly, they disappear when the class is unloaded. It makes sense to imagine them as being somewhere close to the Class instance for the class. Details on how memory is laid out are beyond the reach of the Java application; as a corollary, the JVM specification mandates nothing specific on that subject. Even the "disappearance" of the fields when the class is unloaded cannot be observed directly, but only through GC action, assuming a well-placed finalize() method.

Thomas Pornin