Java variable placed on stack or heap

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.


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.


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

Tags:

Java