Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutoria
Garbage Collection in Java
Last Updated : 04 Jun, 2025
Garbage collection in Java is an automatic memory
management process that helps Java programs run
efficiently. Java programs compile to bytecode that can be run
on a Java Virtual Machine (JVM). When Java programs run on
the JVM, objects in the heap are created, which is a portion of
memory dedicated to the program. Eventually, some objects
will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.
Note: In C/C++, programmers have to manually create and
delete objects, which can sometimes lead to memory leaks
and errors when there is not enough memory available.
This happens when unused objects are not deleted
properly.
Java garbage collector automatically identifies and removes
unused objects, freeing up memory in the heap. It runs in the
background as a daemon thread, helping to manage memory
efficiently without requiring the programmer's constant
attention.
Working of Garbage Collection
Java garbage collection is an automatic process that
manages memory in the heap.
It identifies which objects are still in use (referenced) and
which are not in use (unreferenced).
It removes the objects that are unreachable (no longer
referenced).
The programmer does not need to mark objects to be
deleted explicitly. Garbage collection is implemented within
the JVM.
Types of Activities in Java Garbage Collection
Java heap is divided into generations:
Young Generation: In this new objects are allocated.
Old Generation: In this long-lived objects are stored.
Two types of garbage collection activities usually happen in
Java. These are:
Minor or incremental Garbage Collection (GC): This occurs
when unreachable objects in the Young Generation heap
memory are removed.
Major or Full Garbage Collection (GC): This happens when
objects that survived minor garbage collection are removed
from the Old Generation heap memory. It occurs less
frequently than minor garbage collection.
Key Concepts on Garbage Collection
1. Unreachable Objects
An object becomes unreachable if it does not contain any
reference to it.
Note: Objects which are part of the island of isolation are also
unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.
2. Making Objects Eligible for GC
An object is said to be eligible for garbage collection if it is
unreachable. After i = null, integer object 4 in the heap area is
suitable for garbage collection in the above image.
How to Make an Object Eligible for Garbage Collection?
Even though the programmer is not responsible for destroying
useless objects but it is highly recommended to make an
object unreachable(thus eligible for GC) if it is no longer
required. There are generally four ways to make an object
eligible for garbage collection.
Nullifying the reference variable (obj = null).
Re-assigning the reference variable (obj = new Object()).
An object created inside the method (eligible after method
execution).
Island of Isolation (Objects that are isolated and not
referenced by any reachable objects).
3. Requesting Garbage Collection
Once an object is eligible for garbage collection, it may not
be destroyed [Link] garbage collector runs at the
JVM's discretion, and you cannot predict when it will occur.
We can also request JVM to run Garbage Collector. There
are two ways to do it :
Using [Link](): This static method requests the
JVM to perform garbage collection.
Using [Link]().gc(): This method also
requests garbage collection through the Runtime
class.
[Link]();
// OR
[Link]().gc();
Note: There is no guarantee that the garbage collector will run
immediately after these calls.
4. The finalize() Method (Deprecated in Java 9+)
Before destroying an object, the garbage collector calls
the finalize() method to perform cleanup activities. The
method is defined in the Object class as follows:
@Override
protected void finalize() throws Throwable {
[Link]("GC cleaning up...");
}
Note:
finalize() method is deprecated since Java 9 because it is
unpredictable and can cause performance issues.
Alternatives like try-with-resources or explicit cleanup
methods are preferred.
The garbage collector calls finalize() at most once per
object.
Exceptions thrown in finalize() are ignored.
Employee Management System Using
Garbage Collection Concept
Let's take a real-life example, where we use the concept of the
garbage collector.
Problem Statement:
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:
A parameterized constructor to initialize name and age. The
ID should be initialized in this constructor.
A method show() to display ID, name, and age.
A method showNextId() to display the ID of the next
employee.
Common Beginner Approach (Without Garbage
Collection)
Now any beginner, who does not know Garbage Collector in
Java will code like this:
// Java Program to count number
// of employees working
// in a company
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age) {
[Link] = name;
[Link] = age;
[Link] = nextId++;
}
public void show()
{
[Link]("Id=" + ID +
"\nName=" + name
+ "\nAge=" + age);
}
public void showNextId()
{
[Link]("Next employee id
will be="
+ nextId);
}
}
class UseEmployee {
public static void main(String[] args) {
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
{ // It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4",
23);
Employee Y = new Employee("GFG5",
21);
[Link]();
[Link]();
[Link]();
[Link]();
}
// After countering this brace, X and Y
// will be [Link],
// now it should show nextId as 4.
// Output of this line
[Link]();
// should be 4 but it will give 6 as
output.
}
}
Output:
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=6
Improved Approach Using Garbage Collection and
finalize()
Now garbage collector will see 2 objects free. Now to
decrement nextId, garbage collector will call method to
finalize() only when we programmers have overridden it in our
class. And as mentioned previously, we have to request
garbage collector, and for this, we have to write the following 3
steps before closing brace of sub-block.
1. Set references to null(i.e X = Y = null;)
2. Call, [Link]();
3. Call, [Link]();
Now the correct code for counting the number of employees
(excluding interns):
// Correct code to count number
// of employees excluding interns.
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age) {
[Link] = name;
[Link] = age;
[Link] = nextId++;
}
public void show()
{
[Link]("Id=" + ID +
"\nName=" + name
+ "\nAge=" + age);
}
public void showNextId()
{
[Link]("Next employee id
will be="
+ nextId);
}
protected void finalize()
{
--nextId;
// In this case,
// gc will call finalize()
// for 2 times for 2 objects.
}
}
public class UseEmployee {
public static void main(String[] args) {
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
{
// It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4",
23);
Employee Y = new Employee("GFG5",
21);
[Link]();
[Link]();
[Link]();
[Link]();
X = Y = null;
[Link]();
[Link]();
}
[Link]();
}
}
Output:
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
Note: finalize() is deprecated, this example is for educational
purposes to explain how GC can be used conceptually. But for
production code, use explicit resource management and avoid
relying on finalize().
Advantages of Garbage Collection
The advantages of Garbage Collection in Java are:
It makes java memory-efficient because the garbage
collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector (a part of
JVM), so we don't need extra effort.
Campus Training Program Next Article
JVM Garbage Collectors
C Chirag Agarwal and Gaurav Miglani
166
Similar Reads
1. JVM Garbage Collectors
2. Different Ways to Collect Garbage in Java HotSpot JVM
3. How to make object eligible for garbage collection in Java?
4. Output of Java programs | Set 10 (Garbage Collection)
5. Coding Guidelines in Java
6. How to prevent objects of a class from Garbage Collection in
Java
7. Execution Engine in Java
8. Interesting Facts About Java
9. [Link] Class in Java
10. Java 11 - Features and Comparison
Article Tags : Java java-garbage-collection
Practice Tags : Java
Corporate & Communications
Address:
A-143, 7th Floor, Sovereign
Corporate Tower, Sector- 136,
Noida, Uttar Pradesh
(201305)
Registered Address:
K 061, Tower K, Gulshan
Vivante Apartment, Sector
137, Noida, Gautam Buddh
Nagar, Uttar Pradesh, 201305
Advertise with us
Company Explore Tutorials DSA Data Web
About Us Job-A-Thon Python Data Science & Technologies
Legal Offline Java Structures HTML
ML
Privacy Policy Classroom C++ Algorithms CSS
Data Science
Careers Program PHP DSA for JavaScript
With Python
In Media DSA in GoLang Beginners TypeScript
Machine
Contact Us JAVA/C++ SQL Basic DSA ReactJS
Learning
Corporate Master R Language Problems NextJS
ML Maths
Solution System Android DSA NodeJs
Data
Campus Design Roadmap Bootstrap
Visualisation
Training Master CP DSA Interview Tailwind CSS
Pandas
Program Videos Questions
NumPy
Competitive
NLP
Programming
Deep
Learning
Python Computer DevOps System School Databases
Tutorial Science Git Design Subjects SQL
Python GATE CS AWS High Level Mathematics MYSQL
Examples Notes Docker Design Physics PostgreSQL
Django Operating Kubernetes Low Level Chemistry PL/SQL
Tutorial Systems Azure Design Biology MongoDB
Python Computer GCP UML Social
Projects Network DevOps Diagrams Science
Roadmap
Python Database Interview English
Tkinter Management Guide Grammar
Web Scraping System Design
OpenCV Software Patterns
Tutorial Engineering OOAD
Python Digital Logic System
Interview Design Design
Question Engineering Bootcamp
Maths Interview
Questions
Preparation More Courses Programming Clouds/ GATE 2026
Corner Tutorials IBM Languages Devops GATE CS
Company- Software Certification C DevOps Rank Booster
Wise Development Courses Programming Engineering GATE DA
Recruitment Software DSA and with Data AWS Rank Booster
Process Testing Placements Structures Solutions GATE CS & IT
Aptitude Product Web C++ Architect Course - 2026
Preparation Management Development Programming Certification GATE DA
Puzzles Project Data Science Course Salesforce Course 2026
Company- Management Programming Java Certified GATE Rank
Wise Linux Languages Programming Administrator Predictor
Preparation Excel DevOps & Course Course
All Cheat Cloud Python Full
Sheets Course
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved