Eric said:
That makes sense. So could a single object be on the stack? What about
an object array of constant size? ArrayList[10] or something like that.
Or when you say objects are always stored on the heap, do you really
mean always?
Always. In Java, all objects are dynamically allocated with "new", and
that means that they're always obtained from the heap. And as defined
in section 4.3.1 of JLS3, "An object is a class instance or an array."
So if you have:
void someMethod() {
int[] array;
then the reference variable "array" is on the stack and its initial
value is unknown. It is NOT necessarily null; it could be anything. The
compiler will try to keep you from accessing "array" until you have set
it either to an appropriate array reference or to null.
Now if you have:
void someMethod() {
int[] array = new int[10];
then the reference variable "array" is still on the stack, but now is
initialized to reference an actual array; it has a known value. The
array itself is allocated from the heap. Heap allocations are always
initialized, so all 10 int values are preset to 0.
Now suppose we have a member variable:
public class SomeClass() {
int[] array;
then the object containing this variable will be allocated on the heap
when it is "new"ed so the reference variable "array" is also in the
heap. Heap allocations are always initialized, so "array" starts out as
null.
How about a static member variable:
public class SomeClass() {
static int[] array;
then the class containing this variable will be allocated on the heap
when the class is loaded, so once again the reference variable "array"
is also in the heap. Heap allocations are always initialized, so
"array" starts out as null.