Member Avatar for muaazab

Hi, I am learning to work in JAVA. I have gone through the basic concepts, understood and experimented small codes successfully. The point where I have been stuck is garbage collection, finzalize() method and System.gc() method. I have searched these on Google but all the explanations are in high-tech language which are difficult for me to understand.

My question is, is it necessary to use finalize() method with System.gc() method? What is the use of finalize() method in JAVA? My code snippets are as follows.

public class Student {
 
private String name;
private int rollNo;

private static int countStudents = 0;

// Satndard Setters
public void setName(String name) {

this.name = name;

}

// Masking of class level variable rollNo
public void setRollNo(int rollNo) {

if(rollNo > 0) {

this.rollNo = rollNo;
} else {

this.rollNo = 100;
}
}

//getters of static countStudents variable
public static int getCountStudents() {

return countStudents;
}

//Default constructor 
public Student() {
name = "not set";
rollNo = 100;

countStudents += 1;
}



// Method for display values on screen
public void print() {
System.out.println("Student Name:" +name);
System.out.println("Roll No:" +rollNo);
}

//overriding finalize method of object class
public void finialize() {
countStudents -= 1;
}
} // end of class

The implantation of above class is as follows.

public class Test {
public static void main(String[] args) {

int numObjects;

// Printing current number of objects i.e 0
numObjects = Student.getCountStudents();
System.out.println("Students Objects" + numObjects);


// Creating first student object & printig its values
Student s1 = new Student("ali", 15);
System.out.println("Student:" + s1.toString());


//losing object reference
s1 = null;

//Requiring JVM to run Garbage collector but there is 
//No guarrantee that it will run
System.gc();

//Printing current number of objects i.e unpredictable 
numObjects = Student.getCountStudents();
System.out.println("Students Objects" + numObjects);

} //end of main
} // end of class

Thank You! for your reply/suggestion.

Unless you are doing something very special and complex you will never need to use System.gc(); Java will do its garbage collection when appropriate, there's no reason for you to get involved.
finalize() is not what it seems. It's run when the object is GC'd, which may be any time after you have removed the last reference to it. Depending on how and when the application exits, finalize may never be called. You can't rely on it, so it has no use in ordinary applications.

My best advice: forget about System.gc() and finalize(). You will probably use Java full-time for many years before finding any use for them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.