What is garbage collection in the context of Java?
2017
What is garbage collection in the context of Java?
- A.
The Java Virtual Machine (JVM) checks the output of any Java program and deletes anything that does not make sense at all.
- B.
The Operating System periodically deletes all of the Java files available on the system.
- C.
Any Java package imported in a program and not being used, is automatically deleted.
- D.
When all references to an object are gone, then the memory used by the object is automatically reclaimed.
Attempted by 284 students.
Show answer & explanation
Correct answer: D
In Java, garbage collection is the process of automatically freeing memory used by objects that are no longer needed.
An object becomes eligible for garbage collection when there are no live references to it from any part of the running program.
The JVM reclaims the heap memory used by such unreachable objects automatically.
Key additional points: GC timing is non-deterministic: you know an object is eligible for collection, but you cannot predict exactly when the JVM will run the collector.
Calling System.gc() only requests a collection; the JVM may ignore it.
Garbage collection reclaims memory, not other resources. Always close files, streams, and other non-memory resources explicitly (for example using try-with-resources).
A video solution is available for this question — log in and enroll to watch it.