In the page 91-92:
Local variables are always on the stack, not the heap
Yes sir, I've memorized it for the exam. But... where do the stacks live? Frame. Where do frames live? Isn't that heap? Seems I need some exact definition of the term "heap" here. Okay, I remember somewhere in the book there's a sentence "heap is heap is heap is heap. " Very cute and I loved it, however the cute statement didn't sweep away my curiosity. My understanding to heap is:
I think the "local variables" are also dynamically generated data, if the loader and linker don't put them on the heap, then where?
Just don't forget that while the local variable is on the stack, if the variable is an object reference the object itself will still be created on the heap. There is no such thing as a stack object, only a stack variable....
Yes sir. Here is my question: when an object is generated, which data is exactly stored on the heap? Instance variables and some memory address linking information added by compiler. What else? Local variables are stored in some area other than the heap and then are linked to the object? I'm curious about the memory management of local/instance variables in Java, could anyone please tell me something? Thank you in advance.
[ March 13, 2003: Message edited by: Ellen Zhao ]
The only point of the whole conversation about stacks and heaps is to understand the access mechanism that is used in each case.
The heap is an area of memory that is set aside for the JVM to store objects and whatever else that it needs random access to. As such, anything that is on the heap MUST have a reference to it held somewhere else (like in a variable) in order to find it later.
"The" stack is a last in first out structure that only allows push and pop etc. access.
Some JVMs may choose to locate their Stacks in the area that has been set aside for the heap. It is up to the vendor that wrote the JVM to decide how to implement that. However that is irrelevant to the issue of how the data is accessed. That just means that a reference to the Stack must be held somewhere just like an object. However access to the data in the Stack remains unchanged.
An object is an area of memory (on the heap) that holds the values of the fields of the object. The data inside the object is understood by going to the classfile for the object and looking up the "map" of how an object of this type is laid out - the object's structure.
Not so for local variables. The classfile does NOT keep a map in the classfile of what local variables are/could be/should be. Instead the tracking is dynamic per Frame and so the ordering of the data in the structure becomes important.
The only thing that is "in" a local variable is either a reference to a primitive value, or a reference to an object on the heap. That's it.
Perhaps you would be interested in reading the The JavaTM Virtual Machine Specification. It describes how the actual data management is done.