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.


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 fe 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.


"Method Variables – object(User Defined) – are stored on heap but ..."

Wrong. First, method variables are called local variables.

Let's consider

public static void main(String[] args) {
    List<Integer> model = new ArrayList<Integer>();

Variable model is placed in the stack frame, not on heap. The referenced object generated with new ArrayList<Integer>() is placed in the heap but it is not a local variable.

The 3 things:

  • variable model
  • generated object
  • reference to that object, stored in a variable
  • are quite different, do not mess them up.


    Object are stored in the Heap.

    The object reference stored in the stack.

    Static variable stored in the method area.

    Example abc obj=new abc();

    abc object save in the heap and the object reference is stored in the stack.

    static int i=10;

    i variable stored in the method area.

    链接地址: http://www.djcxy.com/p/79088.html

    上一篇: 结构,堆和堆栈

    下一篇: Java变量放置在堆栈或堆上