Originally posted by Chris Wox: aren't static variables stored in the stack memory ? whears instance variables obviously in the heap ?
No. As Jeff said earlier, declaring something static has no impact on where it is stored.
Objects are always on the heap. Primitives and object references can be on the stack or heap depending on where they are declared.
Joined: May 25, 2006
Originally posted by Scott Johnson:
Primitives and object references can be on the stack or heap depending on where they are declared.
So local variables always on stack and instance/class variables always on heap ?
Joined: Sep 16, 2005
Consider what a drawing of this code would look like:
x = new X(); y = x;
Both variables x and y refer to the same object, so there are three "things" in memory: the object and two variables refering to it:
[var x] ----> [object memory] <--- [var y]
So where in memory are these three things? Objects are always allocated on the heap. What about variables x and y? I avoided declaring them, on purpose. If they are local variables, they are allocated in the method's stack frame -- on the stack. Otherwise, they must be fields: either a static field (class variable) or a non-static field (instance variable). In either case, the memory for the reference is declared on the heap.
End of story? Well, a smart allocator could use what's called escape analysis to determine that an object's lifetime is so short and contained that it could be allocated on the stack. They main thing about this, is that if this happened, your code would never notice the difference -- that's semantics for yah. In these "tree falls in the forest" scenarios, does it make a sound? The answer is: you don't care. As long as the semantics of objects and references are what you know them to be, who cares about some stack -vs- heap implementation details? For example, some garbage collectors keep objects' locations fixed in the heap, others may move them around. Should you care? No, although performance characterics of gc may be relevant... This is like a post I saw earlier this week. The poster wanted to know how much memory a reference took up. I asked why and he said he was just curious. Okay, suppose the answer is "4 bytes", and he walks away with the information, then a month later he finds out it is 8 bytes. What's changed in his conception of how things work? Nothing! So aside from knowing that a reference is cheap to allocate and copy, what use is there in knowing the implementation details? It's like asking what elements are used in making the hardware. How important to programming in Java is knowing what percentage of a chip is silicon?