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.