when declaring variables inside a method, they will be pushed onto the stack when created and popped from the stack when the method returns.
Foo localVariable = new Foo ();
will create a Foo object on the heap, and the link will be saved on the stack. when the method completes, the links are removed from the stack. The garbage collector will do the work of removing Foo from the heap, since no reference to the Foo object will be provided. But,
someStaticVar = localVariable;
calls, someStaticVar refers to the Foo object on the heap. Even after the method exit, someStaticVar will still refer to the Foo object. therefore, the garbage collector does not collect this Foo object. The main thing to remember when the Reference type object is created, the object is created on the heap, and the link is stored on the stack.
The questions are "where is the static field stored?", The fields of the object instance are stored on the heap, the local variables are stored in stacks, but where is the "static variable exists in memory? "
source share