Garbage collection is the part of effective memory management.
Java provides automatic garbage collection. Thus it frees the programmer from the headache of adding any memory management logic.
Before we proceed, can you tell me?
Where is the objects that you create gets stored?
Always remember, any object created in java gets its memory space in heap.
I guess, now you can think of where entire garbage collection process takes place. Definitely, its heap.
How garbage is collected in java?
Whenever there is any object that has no reference and is lying unreachable from the java program, it automatically qualifies for garbage collection.
When does garbage collector run?
Garbage collector is under the control of JVM. So it is upto JVM to decide when to run garbage collector. Whenever JVM gets the feeling that it is running out of the memory, it starts garbage collection to claim the space occupied by objects residing in heap without having any reference.
*Note : free() is used in C and delete() in C++ to collect garbage while java collects it automatically
Disadvantage of Java's Garbage collection process
The only downside of Garbage collector is that it can't be controlled completely by programmer. You may give instruction to run garbage collection process but its up to the JVM to start the process at its own whim.
Advantages of Java's Garbage collection process
Java provides better memory management due to automatic garbage collection technique.
It frees the programmer from taking pain to write the logic to collect garbage (but programmers can give instruction to JVM to run garbage collector, if they want).
Which method is called before the garbage collection occurs?
finalize() method is called before any garbage is collected. We will read the importance of this method in the next chapter.