


There's no reason to do so, since the executable code is read-only. Note also that the executable code is not copied for each invocation of the method. The executable code exists exactly once for each method, and it goes in the method area which is part of the heap.

There's no reason that the executable code has to live in the same region of memory as the data it refers to. In a method code, we not only create objects but we also create local variables, so we can't say that whole method code will go on heap,i think so. It's only local variables that go on the stack. All the executable code for method bodies goes on the heap. In method code, only if you create any object then it will go in heap else all local variables will go in stack.įalse, what Campbell stated was correct. B nh stack là mt phn ca b nh cha mehtod, local variable và variable tham chiu. Local variables and calls to methods: stackĪnd as Henry has pointed out some objects can be created on the stack in Java 6. Java cng s dng c b nh stack và heap cho các nhu cu khác nhau.Objects, including instance fields: heap.Class objects, including method code and static fields: heap.And primitive types can be stored on the heap if they are members of a class or object. So for now, it's safe to say that all objects are always on the heap, and only local variables are on the stack.) The reference itself could be stored on the heap if it is a member of a class or object, or on the stack if it is a local variable in a method. I don't know if that made it into the spec, or, even if it did, if any implementations take advantage of it. (Note that there was some talk of including or allowing escape analysis in Java 7, so that implementations would be allowed to store objects on the heap if they could verify that the object was never used outside that method invocation. And all class definitions go on the heap (in a special area called the method area), which includes constants defined in those classes. And note that variables never store objects they only hold primitives and references. The rule, however, is quite simple: Local variables (including method parameters) go on the stack. I don't know what you mean by "direct values," as that's not part of any standard Java lexicon, and whatever it means, I don't know why you would think that means they go on the stack. I have doubt as per my knowledge interfaces can have constants which are direct values, so it should be in the stack.
