Java OOP – Garbage Collection
September 1, 2020 2 min read

The process by which the programs perform memory management automatically is called Garbage Collection in Java. The Garbage Collector(GC) reclaim the memory by finding the unused objects and deleting them. Dynamic memory allocation of objects is achieved using the new operator that uses some memory and the memory remains allocated until there are references for the use of the object.
The memory occupied by the object can be reclaimed when there are no references to an object, and it is assumed to be no longer needed. There is no explicit need to destroy an object as Java handles the de-allocation automatically.
The technique that accomplishes this is known as Garbage Collection. When there is no memory left in the system to allocate, programs that do not de-allocate memory can eventually crash. These programs are said to have memory leaks.
Garbage collection in Java happens automatically during the lifetime of the program. It is eliminating the need to de-allocate memory and thereby avoiding memory leaks.
Let’s see some cases of Garbage Collection with examples in java.
Case I

Object is a class. Even after garbage collector taken the unused objects when making the objects, Method finalize() will run a moment before the memory get deleted. Here the running of the code i=314 will stop and an error will occur because of the less space in the heap.
Case II

Garbage collector starts with the starting of JVM. But the garbage collector deletes objects when it has a law memory.
Case III

System.gc() is the method that gives to the garbage collector to delete the objects. Therefore even it has memory, objects will be deleted.
Rules for garbage collection:
Rule No.1 – Null referencing

In null referencing c1 reference is making to null and then the object will be automatically eligible for the garbage collector.
Rule No.2 – Re-Assigning

First 100 is given as the argument for the c1 reference and then again 200 is given as the argument for c1. Because of this the object that has the argument 100 is getting eligible to the garbage collector.
Rule No.3 – Local Scope

The object created with the c1 reference is situated in a local scope. c1 reference is only situated in that block. That means the references made in the local scope can access only inside that block. Then that object is eligible for garbage collector.
Rule No.4 – Isolate

If we make many objects by the same reference and when finally make that reference null as shown in the example, all of those objects are eligible for garbage collector.
Our OOP tutorial has been finished with this article. You can visit Project Guide for the projects that you need to study. And also put a comment if you have any doubt or anything comes to your mind after reading our articles.
Thank you.


