1. Garbage Collection
new keyword is used to allocate
memory in heap at runtime for the
objects. Constructor is called at the
time of object creation automatically.
We were using free() function in C
language and delete() in C++ to de-
allocate memory at runtime. But, in
java it is performed automatically. So,
java provides better memory
management.
In Java, memory de-allocation
2. Garbage Collection
In Java, garbage means unreferenced
objects.
When to perform memory de-
allocation? When no references to an
object exist, that object is assumed to
be no longer needed, and the memory
occupied by the object can be de-
allocated.
The garbage collector (java program)
finds these unused objects and
deletes them to free up memory.
3. Garbage Collection
Garbage collection occurs sporadically
(irregular intervals) during the
execution of the program.
The main objective of Garbage
collector is to free heap memory by
destroying unused objects.
To make objects as unreferenced,
assign null to objects.
Eg:
Employee e=new Employee(); e=null;
4. Garbage Collection
System.gc() or
Runtime.getRuntime().gc(), these two
methods are used to call garbage
collector in your Java program.
Advantages of garbage collection
◦ It makes java memory efficient because
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
to make extra efforts.