InterviewSolution
| 1. |
Garbage Collection in Java |
|
Answer» The Garbage collection in Java DESTROYS all those objects that are not in use any more. So basically, garbage collection helps free the heap memory by removing the unreachable objects i.e. the objects that don’t have any REFERENCE to them. The different ways that an object is made eligible for garbage collection by the programmer is given as follows:
After an object is eligible for garbage collection, the garbage COLLECTOR can be run by requesting the Java Virtual Machine. This can be done using the following methods:
A PROGRAM that demonstrates running the garbage collector by requesting the Java Virtual Machine is given as follows: public class Demo { public static void main(String[] args) throws InterruptedException { Demo obj = new Demo(); obj = null; System.gc(); } @Override protected void finalize() throws Throwable { System.out.println("The garbage collector is called..."); System.out.println("The object that is garbage collected is: " + this); } }The OUTPUT of the above program is as follows: The garbage collector is called... The object that is garbage collected is: Demo@7978f9b4 |
|