#. There are two types of memory in java. They are called stack and heap respectively.
The stack is the program memory space, so all basic types and object references are stored in the stack.
The heap is where the Java virtual machine stores objects. It is a huge memory. When you create an object, the Java virtual machine puts the object into the heap and the address of the created object into the stack.
Therefore, references to basic types and objects are stored in the stack; objects are stored in the heap.
#. Garbage collection mechanism in java
When you new a new object, Java allocates the necessary memory. When you finish using an object, Java's garbage collector reclaims the memory for you.
Garbage collection runs in the background in the form of threads, looking for objects that have no useful references. Once found, the objects are destroyed and the memory is reclaimed.
Garbage collection is implemented between Java virtual machines. They usually have the same steps. First, the garbage collector obtains a snapshot of running threads and all loaded classes.
Then all objects involved in the thread are marked as recently used. When all objects that may be involved are marked, the remaining unmarked ones are discarded.
In order to help the virtual machine, it is a good practice to proactively remove some objects that are no longer needed. This can be achieved by setting the reference to null.
e.g.:
Text t = new Test();
t.someAction();
//all done
t = null;