Originally posted by Rajashekar Subramany:
This is what i think. Do correct me if am wrong.
You're correct in your thinking, although your example has problems.
I think what confuses people is the oft-repeated, but frankly
wrong, statement that "references are on the stack, and objects are on the heap." What goes on the stack are
local variables. Any variable that you declare inside a method is on the stack. This is true for all kinds of variables, primitive and refererence. It has nothing to do with the type of the variable -- only where it's defined.
Instance variables -- non-static variables declared
outside of any method -- are part of an object. They
are the object, in fact. When we say that "an object is allocated on the heap", what we're saying is that memory to hold the instance variables of that object is allocated in the heap area. Again, the data type of the variables is irrelevant: primitive members and reference members alike are stored in the object's same little block of memory on the heap.
Anything created by "new" is an object; this include arrays. Arrays are instances of special classes that extend java.lang.Object, just like any other class. These objects, just like all other objects, are allocated on the heap, and that allocated memory contains all their data. The array elements are like the "member variables" of the array, and as such, they are part of the object living on the heap. I should say here, to be precise, that nowhere in the JLS or VM spec does it say anything about how objects are laid out in heap memory. You have to realize that much of what we're saying here is conceptual rather than a description of some physical reality in the computer.
Anyway, based on the "mooseArray" example, we can't tell where mooseArray is, because if we only see that one line of code, we don't know if it's in the body of a method or at class level, and it's really this kind of one-line example that gives rise to the confusion we're trying to remedy.
The short answer: arrays, including the element data they contain, are objects allocated on the Java heap.
[ January 21, 2006: Message edited by: Ernest Friedman-Hill ]