#. There are two types of memory in java. Stack and heap respectively ).
Stack is the program memory space. Therefore, all basic types and object references exist in the stack.
Heap is the storage object of the Java Virtual Machine. It is a huge memory. When you create an object, the Java Virtual Machine puts the object into the heap, and puts the address of the created object into the stack.
Therefore, the reference of the basic type and object is stored in the stack, and the object is stored in the heap.
#. Garbage collection mechanism in java
When you create a new object, java allocates the necessary memory. When you use up an object, the java Garbage Collector recycles the memory for you.
Garbage collection runs in the background in the form of a thread, searches for objects without reference, destroys the objects, and recovers the memory.
Garbage collection is implemented between Java virtual machines. They usually take the same steps. First, the garbage collector obtains the snapshot of the running thread and all loaded classes,
Then, all objects involved in the thread are marked as recently used. When all objects involved are marked, the remaining objects that are not marked are discarded.
To help virtual machines, it is a good practice to remove unnecessary objects by setting the reference to null.
Eg:
Text t = new Test ();
T. someAction ();
// All done
T = null;