Where does class, object, reference variable get stored in Java. In heap or in stack? Where is heap or stack located?

I understand that variables of a method are stored in stack and class variables are stored in heap. Then where does the classes and objects we create get stored in Java?


Solution 1:

Runtime data area in JVM can be divided as below,

  1. Method Area : Storage area for compiled class files. (One per JVM instance)

  2. Heap : Storage area for Objects. (One per JVM instance)

  3. Java stack: Storage area for local variables, results of intermediate operations. (One per thread)

  4. PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread)

  5. Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread)

Solution 2:

Following are points you need to consider about memory allocation in Java.

Note:

Object and Object references are different things.

  1. There is new keyword in Java used very often to create a new object. But what new does is allocate memory for the object of class you are making and returns a reference. That means, whenever you create an object as static or local, it gets stored in heap.

  2. All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap.

  3. Classes loaded by ClassLoader and static variables and static object references are stored in a special location in heap which permanent generation.

  4. Local primitive variables, local object references and method parameters are stored in stack.

  5. Local Functions (methods) are stored in stack but static functions (methods) goes in permanent storage.

  6. All the information related to a class like name of the class, object arrays associated with the class, internal objects used by JVM (like Java/Lang/Object) and optimization information goes into the Permanent Generation area.

  7. To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems.

Solution 3:

All objects in Java are stored on the heap. The "variables" that hold references to them can be on the stack or they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.

The Class objects that define Classes are also heap objects. They contain the bytecode that makes up the class (loaded from the class files), and metadata calculated from that.