Garbage Collection(GC) in Java Tutorial


In the Java programming language, dynamic allocation of objects is achieved using the new operator. An object once created uses some memory and the memory remains allocated till there are references for the use of the object. When there are no references for an object, it is assumed to be no longer needed and the memory occupied by the object can be reclaimed.

There is no explicit need to destroy an object as java handles the de-allocation automatically. The technique that accomplishes this is known asGarbage Collection.
Programs that do not de-allocate memory can eventually crash when there is no memory left in the system to allocate. These programs are said to have memory leaks 

 

In Java,Garbage collection happens automatically during the lifetime of a java program, eliminating the need to de-allocate memory and avoiding memory leaks.

In C language, it is the programmer’s responsibility to de-allocate memory allocated dynamically using free() function.


Note : All objects are created in Heap Section of memory. 
Step 1) Copy the following code into a editor
01.class Student{
02.int a;
03.int b;
04. 
05.public void setData(int c,int d){
06.a=c;
07.b=d;
08.}
09.public void showData(){
10.System.out.println("Value of a = "+a);
11.System.out.println("Value of a = "+b);
12.}
13.public static void main(String args[]){
14.Student s1 = new Student();
15.Student s2 = new Student();
16.s1.setData(1,2);
17.s2.setData(3,4);
18.s1.showData();
19.s2.showData();
20.//Student s3;
21.//s3=s2;
22.//s3.showData();
23.//s2=null;
24.//s3.showData();
25.//s3=null;
26.//s3.showData();
27.}
28.}
Step 2) Save, Compile and Run the code.  As shown in the diagram , two objects and two reference variables are created.
java-garbage-collection

Step 3) Uncomment line # 20,21,22. Save , compile & run the code.
Step 4)  As show in diagram below, two reference variables are pointing to the same object.
java-garbage-collection-1
Step 5)  Uncomment line # 23 & 24. Compile , Save & Run the code

Step 6) As show in diagram below , s2 becomes null , but s3 is still pointing to the object and is not eligible for garbage collection.
java-garbage-collection-3
Step 7) Uncomment line # 25 & 26 . Save , Compile & Run the Code
Step 8) At this point there are no references pointing to the object and becomes eligible for garbage collection. It will be removed from memory and there is no way of retrieving it back.
java-garbage-collection-4

Garbage Collection Important Points to Note:


1) If you want to make your object eligible for Garbage Collection , assign its reference variable to null.
2) Primitive types are not objects. They cannot be assigned null.
java-primitive-data-type


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email