java

Java variable placed on stack or heap


I don't have much idea on Java.

I was going through few links and found blog says "Java Primitives stored on stack", which I feel it depends on instance variable or local variable.

After going through several links my conclusion is,


Class variables – primitives – are stored on heap as a part of Object which it contains.

Class variables – object(User Defined) – are stored on heap as a part of Object which it contains. This is true for both reference and actual object.

Method Variables – Primitives – are stored on stack as a part of that stack frame.

Method Variables – object(User Defined) – are stored on heap but a reference to that area on heap is stored on stack as a part of that stack frame. References can also be get stored on heap if Object contains another object in it.

Static methods (in fact all methods) as well as static variables are stored in heap.

Please correct me if my understanding is wrong. Thanks.


Solution

  • There are some optimizations in the JVM that may even use the Stack for Objects, this reduces the garbage collection effort.

    Classes are stored on a special part of the heap, but that depends on the JVM you use. (Permgen f.e. in Hotspot <= 24).

    In general you should not have to think about where the data is stored, but more about the semantics like visibility and how long something lives. Your explanation in the questions looks good so far.