53

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?

4
  • 2
    Have a look at this article, the formal definition can be found in the JVM Spec Commented Nov 29, 2012 at 11:18
  • 3
    What many be confusing is that objects are stored on the heap but the reference to that object which is what you use in Java, can be on the stack. Similarly, a reference to a Class object can be on the stack, the Class object is on the heap, but the Class object is meta data about the class and the actual code is in the PermGen. Commented Nov 29, 2012 at 11:38
  • 1
    @PeterLawrey: PermGen is considered part of the heap, right? Commented Nov 29, 2012 at 11:43
  • 1
    @Thilo AFAIK, its not part of the maximum heap size so I would say not. It is a management memory space. Commented Nov 29, 2012 at 11:44

8 Answers 8

71

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)

Sign up to request clarification or add additional context in comments.

Comments

49

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.

7 Comments

This answer is helpful, but I am afraid I am gonna need a reference link.
@mudit_sen - not sure what you refer to, when declaring "Local Functions". if you are talking about instance methods, well those references must lie on heap. And moreover methods are never part of the object structure because they are not objects by themselves. They exist as instruction codes on the code segment and its the starting address of the method that the instance on the heap points to.
@supi - As mentioned in the link, blog.codecentric.de/en/2010/01/… , the Runtime Data Area contains the Method Area. It has a mice image explaining the Runtime Data Area. The method code exists in this Method Area. What do you mean by Code Segment ? Is that some part of memory in Method Area ? Also when you say that the instance on the heap points to starting address of the method, does that mean that all the instances of a particular class in the HEAP would contain the starting address of the method from the Method Area ? Please could you clarify ?
@RohitT Yes all instances of a class on managed heap should be pointing to the starting address of the corresponding method code in the method area. The point being the method code doesn’t change, be it static or an instance method. So there is no pointing in wasting memory space by replicating this in each instance. The only things that change for the method are the arguments and the return value, which by the way are made available on the stack.
@RohitT Code segment is like a general term to denote areas where instruction codes reside, like method area. Upon compilation a typical class object will eventually be transformed to bootstrap code that will allocate a certain address as well as memory within the unmanaged heap to store the class object, along with instructions to initialise its static attributes and its method code residing with the method area of each such class object (I learned this implementation details from the diagram and article you shared - thanks)
|
18

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.

Comments

7

The Stack section of memory contains methods, local variables and reference variables.

The Heap section contains Objects (may also contain reference variables).

after short google, I found a link to describe it, yes a youtube video link. ^_^

http://www.youtube.com/watch?v=VQ4eZw6eVtQ

5 Comments

what do you mean by "the stack contains methods" (other than local variables)?
The video is unavailable. Could you give us another link?
The video is no longer available. Next time, consider summarizing the video in your answer. That way, if the video becomes unavailable, it doesn't affect your answer as significantly.
The stack does not contain methods.
@Kent - the stack section don't contain methods as such, only the data(like local variables, temporary results etc) prevailing to methods currently in execution. The actual method instruction code go into the method area and not the stack.
5

The concept is quite simple :

  1. Instance variables (primitive, Wrapper classes, references, objects (non-static)) - Heap
  2. Local Variables , references - stack
  3. Other data objects like : Class metadata, JVM code, static variables, static object references, static functions etc which earlier used to be in Permgen Space (till Java 7) are now being moved to Metaspace in JAVA 8.

PS : Metaspace is part of native memory, so no need to worry about OOM:Pergem Exeption now.

For more details : https://siddharthnawani.blogspot.com/

Comments

3

Local variables(method variables) + methods live on the stack. While Objects and their instance variable live on the heap.

Now, Reference variable can be local variable(if created inside method) or instance variable(if created inside class, but outside method). So reference variable can be anywhere, either stack or heap.

1 Comment

Methods do not live on the stack.
2

According to JVM Specification,

The classes and it's own constant pool, i.e static variables are stored in Method Area. Here class means nothing but bunch of fields, methods and constants, these methods are in the form of instructions are stored in Method Area and can be identified by an address.

Objects are nothing but a filled class template that will be created in Heap Area, but the object reference is created in Stack.

public class Sample{
int field;
static int constant;
public void test(){
int localVariable=10;
Sample samp=new Sample();
  }
}

In the example, sample.class will go to Method Area, that means 'field', 'constant' and method 'test' are allocated in Method Area.

When the execution is started, The object created by new Sample() will go to Heap but 'samp' is just a object reference which goes to stack and holds the address of object which is present in the Heap

For more information please check this link, JVM Specification

1 Comment

"field" will be stored in heap not method area as it neither run-time constant nor static variable .
0

In Java, a variable can either hold an object reference (s in String s="OOO" holds the reference to the object "OOO") or a primitive value (i in int i=10 holds 10). These variables can either be on the heap or the stack, depending on whether they are local or not and which flavor of the JVM you are using.

In the Java Virtual Machine 8 specification document (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html), the memory organization pertaining to this is as follows.

  1. Every Java thread has its own JVM stack.

    It holds local variables and partial results, and plays a part in method invocation and return.

    There may be object references as well in the stack. The specification does not differentiate between a primitive variable and a reference variable as long as it is local. This stack is used using units of data called frames. However,

    Because the Java Virtual Machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated.

    Therefore, it is upto the implementation of the JVM specification (like OpenJDK or Oracle), where the frames are located.

  2. Every JVM instance has a heap. The heap is

    ... the run-time data area from which memory for all class instances and arrays is allocated.

    The actual memory holding the objects' data resides on the heap. The heap is shared among all the JVM's threads. This also includes object references which are part of objects ie instance variables.

    For example, take the following classes.

    class Moo{ private String string= "hello"; } class Spoo{ private Moo instanceReferenceVariable = new Moo(); public void poo(){ int localPrimitiveVariable=12; Set<String> localReferenceVariable = new HashSet<String>(); } }

    Here the object being referred to by the variable instanceReferenceVariable
    would be on the heap, and hence all the instance variables of this object, like string, will also be on the heap. Variables localPrimitiveVariable and localReferenceVariable will be on the stack.

  3. Method Area: The method area is a restricted part of the heap which

    ... stores per-class structures such as the run-time constant pool, field and method data, and the code for methods and constructors, including the special methods used in class and instance initialization and interface initialization.

  4. Run-time constant pool: This is a part of the method area.

Hope this was able to clarify things.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.