Best Regards,<br />Vipin<br />MCA, SCJP5, SCWCD in progress
Joined: Aug 24, 2008
AS I Think Primitives are stored on the stack, objects in the heap space.
int j = 20; will be stored on the stack, because the variable itself holds the value and it's much faster, but if you wrap it: Integer p = new Integer(20); then it's stored in the heap space because it's now an object.
I have doubt as per my knowledge interfaces can have constants which are direct values, so it should be in the stack. Please correct if I am wrong here.
You are wrong here. 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.
The rule, however, is quite simple: Local variables (including method parameters) go on the stack. Everything else goes on the heap. And note that variables never store objects; they only hold primitives and references. So all objects go on the heap. And all class definitions go on the heap (in a special area called the method area), which includes constants defined in those classes.
(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. I don't know if that made it into the spec, or, even if it did, if any implementations take advantage of it. So for now, it's safe to say that all objects are always on the heap, and only local variables are on the stack.)
That video is somewhere between misleading and just plain wrong.
It seems to suggest that a method's executable code goes on the stack, which is false. If that's not what it's trying to say, it should be clearer in how it's worded.
It also talks about stack variables being "flushed", as if there's some active process to remove or clear them. That's not how it works. The stack pointer simply gets reset to its previous value. The old values of the variables are still there on the stack until another stack frame overwrites them.