Java_19_Garbage
Java_19_Garbage
1) By nulling a reference:
Employee e=new Employee();
e=null;
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class
as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by
new keyword. So if you have created any object without new, you can use finalize
method to perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
Output:
object is garbage collected
object is garbage collected
Real-World Example
Let’s take a real-life example, where we use the concept of the garbage collector.
Question: Suppose you go for the internship at GeeksForGeeks, and you were
told to write a program to count the number of employees working in the
company(excluding interns). To make this program, you have to use the concept of
a garbage collector.
This is the actual task you were given at the company:
Write a program to create a class called Employee having the following data
members.
1. An ID for storing unique id allocated to every employee.
2. Name of employee.
3. age of an employee.
Also, provide the following methods:
1.A parameterized constructor to initialize name and age. The ID should be
initialized in this constructor.
2.A method show() to display ID, name, and age.
3.A method showNextId() to display the ID of the next employee.
Now any beginner, who doesn’t know Garbage Collector in Java will code like this:
// Java Program to count number
// of employees working
// in a company
class Employee {
class Employee {
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4