What is Garbage ?
Java provides the means to create an object, but the language doesn't provide the means to destroy the object explicitly.
As long as the reference to an object is present in the program , JVM ensures that the object exists.
1. If Java provided the means to destroy the object , it would produce unpredictable result if program calls any method on the reference of the object (destroyed already) because reference still existed. In this case these reference are called dangling reference.
Reference ---------------------> Dead or Destroyed Object = Dangling Reference
So Java eliminates dangling reference problem by disallowing the destruction of objects explicitly.
2. If Java provided the means to destroy objects explicitly then program would need to keep track all the objects created and destroyed which are no longer used . In this scenario if program somehow lose the track of object it has created the that object cannot be destroyed. And if the object is never destroyed , the memory used by the object cannot be reused by the program causes memory leak.
A program that loses track of objects before it destroys them suffers from a memory leak . If we run a program that has a memory leak for a very long time, it is quite possible that it will exhaust all the available memory and eventually fail because no new objects can be created.
An unreferenced object is called garbage and the process of finding all the unreferenced objects and reclaiming the storage is called garbage collection .