8.7 Garbage Collection

Look at the following code :

Rectangle rect = new Rectangle(); //Statement 1

garbage-collection

  • Statement 1 does two things:
    1. A rectangle object is created.
    2. A reference to that object is saved in the reference variable rect.
rect = null; //Statement 2

garbage collection

  • Statement 2 assigns the value null to rect. When this happens, the reference to the object is lost. Since there is no reference to the object elsewhere, it is now garbage.

 

The object still exists in memory. The memory it consists of will eventually be recycled by the garbage collector, and will be made available for new objects.
Under most circumstances, when you are finished with an object you have created, Java can determine that the object no longer has any live references to it.

As a program runs, Java periodically looks for unused objects and reclaims the memory that those objects are using. This process is called garbage collection and occurs without requiring any programming on your part. You don’t have to explicitly free the memory taken up by an object.