overexchange
overexchange

Reputation: 1

How arrays use stack and heap space in Java?

As part of learning, from the below example,

enter image description here

My question:

Withe given memory layout of array declaration/definition, I would like to understand, Which memory space will be part of Stack space & Heap space? To be precise, Where does the below memory space(part of above diagram) sit?

enter image description here

Upvotes: 2

Views: 531

Answers (2)

Chris K
Chris K

Reputation: 11925

Objects are always declared on the heap. Only references to objects are past around on the stack via method variables and parameters.

Thus the object graphs that you have diagrammed above will be stored on the heap and references to those objects will only exist on the stack during method invocation if and only if they have a parameter or variable that points to an object in the above diagrams.

JVM optimisations may vary this slightly under the hood, such as using registers instead of a stack or inlining an object as it can be shown to never escape a method call etc. However those optimizations may or may not occur, and they are not visible from the Java language level. Thus the above rule of the Java language holds, objects on the heap and method parameters/fields on the stack. Parameters and fields can never hold an object, only references to an object.

Upvotes: 3

TheMonkWhoSoldHisCode
TheMonkWhoSoldHisCode

Reputation: 2332

THUMB-RULE - All objects are created on the heap irrespective of where they are instantiated.

Upvotes: 1

Related Questions