I think the answer to this has been posted on this site only albeit in a different section. The answers lies in predictability of the lifetime of a variable. For example, all variables declared within a method have a predictable lifetime(they will exist as long as the method finishes execution). Hence they are stored in a stack.So, a stack is a memory management structure used to store "predictable lifetime" variables.References to objects, and variables declared within the methods are stored in a stack.
All instance variables and objects have unpredictable lifetime, so they are stored in the heap.I think drawing an anology with the literal meaning of stack and heap might help you to understand this concept.
Joined: Mar 10, 2006
Btw, I am only quoting someone else. I don't deserve any credit other than seeking to help you out :-)
Joined: Jan 19, 2006
Concerning your affirmation :
For example, all variables declared within a method have a predictable lifetime(they will exist as long as the method finishes execution). Hence they are stored in a stack.
References to objects, and variables declared within the methods are stored in a stack.
I think your affirmation is not exactly correct, think about objects declared within a method. Even after the method execution finishes, the object created within a method still remains alive probably waiting for garbage colletion. So, its life time is unpredctable. That's why Java puts all objects within heap.
Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names, with a first and a last name.
Originally posted by Edisandro Bessa: In summary, reference variables are always created on the heap, regardless whether or not they are inside a method.
Sorry, but this is wrong. All objects are created on the heap; this includes, of course, the contents of all objects (their member variables). But local variables, regardless of their type, are always on the stack. The object a local reference variable refers to is, like all objects, on the heap; but local variables of every type, reference or primitive, are on the stack.
As to your correction of someone's correction: that's really not right either. When a variable goes out of scope, it's gone. It doesn't matter what kind of variable it is. This is quite apart from the lifetime of any object a variable might have referred to. As soon as an object is unreachable, it's gone. The JVM may grind it to a pulp instantly, or it may never collect it. But just the same, it's gone to your program, and that's perfectly determinate.